【问题标题】:c++ frequently open and close iostream will affect IO performance?c++频繁打开关闭iostream会影响IO性能吗?
【发布时间】:2021-12-29 03:34:34
【问题描述】:

如果我想像日志功能一样频繁写入文件,哪种方式更好?

  1. 当我需要写入时,打开 iostream 并在完成后关闭
void log(const string& s){
    iostream ios(log_path);
    ios << s;
    ios.close();
}
void main(){
    while (need_to_log) {
        log(some_string);
    }
}
  1. 开始时将文件描述符保存为某个全局变量,在需要写入时使用它,在程序关闭时关闭。
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 取决于您认为“重要”的内容,也取决于使用的操作系统。
  • 没有iostream::close()

标签: c++ iostream


【解决方案1】:

是的,可能会有很大的不同——如果你的应用程序大部分时间都花在日志记录上

打开和关闭文件需要系统调用。特别是要关闭一个文件,需要刷新ostream 的内部缓冲区,这需要另一个系统调用,并且可能还需要写入相对较慢的磁盘。

相反,如果您保持流打开,operator&lt;&lt; 只会写入内存中的内部缓冲区,并且仅在缓冲区满时才将其写入。这更有效,但这也意味着您可能会看到文件中出现日志行的延迟。将std::flush 发送到流中以提前刷新;请注意,写入std::endl(而不是简单的'\n')也会触发刷新。

【讨论】:

    猜你喜欢
    • 2016-05-10
    • 1970-01-01
    • 2011-02-22
    • 2013-12-31
    • 2021-04-18
    • 2011-04-05
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    相关资源
    最近更新 更多