f1msch
f1msch

Reputation: 659

c++ frequently open and close iostream will affect IO performance?

If I want to write into a file frequently like the function of logging, which is the better way?

  1. when I need to write, open iostream and close when it is done
void log(const string& s){
    iostream ios(log_path);
    ios << s;
    ios.close();
}
void main(){
    while (need_to_log) {
        log(some_string);
    }
}
  1. save the file descriptor as some global variable at the beginning, use it when needed to write and close when program closes.
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

Answers (1)

Thomas
Thomas

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

Related Questions