Reputation: 659
If I want to write into a file frequently like the function of logging, which is the better way?
void log(const string& s){
iostream ios(log_path);
ios << s;
ios.close();
}
void main(){
while (need_to_log) {
log(some_string);
}
}
iostream ios(log_path);
void log(const string& s){
ios << s;
}
void main(){
while (need_to_log) {
log(some_string);
}
ios.close();
}
Will there be a significant performance difference between those two?
Upvotes: 0
Views: 300
Reputation: 181725
Yes, there will probably be a significant difference – if logging is what your application is spending most of its time on.
To open and close files requires a system call. To close a file, in particular, requires the internal buffer of the ostream
to be flushed, which requires another system call, and possibly also writing to a relatively slow disk.
In contrast, if you keep the stream open, operator<<
just writes to an internal buffer in memory, and only writes it out when the buffer gets full. This is more efficient, but it also means you might see a delay in log lines appearing in the file. Send std::flush
into the stream to flush earlier; note that writing std::endl
(as opposed to simply '\n'
) also triggers a flush.
Upvotes: 3