c++ - 为什么 ostringstream 比 ofstream 快

标签 c++ filestream iostream

要将多条数据写入文件,我有两种方法:

  1. 直接一个一个写入ofstream

    ofstream file("c:\\test.txt");
    for (int i = 0; i < 10000; ++i)
    {
        file << data[i];
    }
    
  2. 先写入istringstream,然后一次性写入ofstream

    ostringstream strstream;
    for (int i = 0; i < 10000; ++i)
    {
        strstream << data[i];
    }
    ofstream file("c:\\test.txt");
    file << strstream.str();
    

毫不奇怪,第二种方法更快,事实上,在我的 HP7800 机器上,它比第一种方法快 4 倍。

但是为什么?我知道 ofstream 在内部使用 filebuf,而 ostringstream 使用 stringbuf - 作为缓冲区,它们都应该驻留在内存中,因此应该没有区别。

引擎盖下有什么区别?

最佳答案

您是否经常使用 std::endl 而不是 '\n'std::endl 做两件事:它向流中插入一个 '\n' 然后将缓冲区刷新到磁盘。我已经看到代码说这样做会严重影响性能。 (修复后代码运行速度提高了 5-10 倍。)
刷新到字符串缓冲区比刷新到磁盘要快得多,所以这可以解释你的发现。

如果不是这种情况,您可能会考虑增加缓冲区大小:

const std::size_t buf_size = 32768;
char my_buffer[buf_size];
ofstream file("c:\\test.txt");
file.rdbuf()->pubsetbuf(my_buffer, buf_size);

for (int i = 0; i < 10000; ++i)
{
    file << data[i];
}

关于c++ - 为什么 ostringstream 比 ofstream 快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5192239/

相关文章:

c++ - Q_DECLARE_METATYPE 期望 ctor、dtor 或之前的类型转换; token

c++ - 将任何类型的值存储为 C++ 模板化工厂方法中最初提供的类型?

c++ - 在 g++ 和 msvc 中使用 ifstream 读取文件的差异

c# - C#文件流在写/读操作完成之前不会阻塞

c++ - ostream::write 实际写入了多少字节?

c++ - 如何在 C++ 中检查 std::cout 是否重定向到文件?

c++ - 如何在访问指针值时保护应用程序免受读取访问冲突?

c++ - 使用 C++ (Win32) 导入 DLL

javascript - node.js 修改文件数据流?

c++ - 即使使用 ios::binary 也无法以二进制模式写入文件