gpt4 book ai didi

c++ - 逐行写入文件并一次写入整个文本

转载 作者:行者123 更新时间:2023-11-30 01:20:39 24 4
gpt4 key购买 nike

我总是说文件 io 进程是最慢的。但是,当我测试以下两个过程时:

场景 1:

test.open("test.xml",fstream::out);
for(int i=0;i<1000;i++)
{
test<<"<p> attr1=\"test1\" attr2=\"test2\" attr3=\"test3\" attr4=\"test4\">test5</p>\n";
}
test.close();

场景 2:

test.open("test.xml",fstream::out);
stringstream fileDataStr;
for(int i=0;i<1000;i++)
{
fileDataStr<<"<p> attr1=\"test1\" attr2=\"test2\" attr3=\"test3\" attr4=\"test4\">test5</p>\n";
}
test<<fileDataStr;
test.close();

我预计 senario1 会更慢,因为它执行 1000 个文件 io,但测试结果表明它与场景 2 具有相同的速度(就 clock_t 而言)。为什么会这样,是否与文件读取中的操作系统优化有关? getline while reading a file vs reading whole file and then splitting based on newline character

编辑:根据@irW 的建议

  string fileDataStr;

改为

stringstream fileDataStr;

最佳答案

由于 std::ofstream 缓冲输出的方式,您最终在这两种情况下执行完全相同数量的 IO。 (通常,无论如何——一个实现可以在以下情况下优化事情你输出一个很长的字符串。)唯一的区别是第二种情况,你引入了一个额外的中间体buffer,就是多了一点拷贝,多了一些动态分配。 (有多少动态分配取决于实现,但不应该太多。)

关于c++ - 逐行写入文件并一次写入整个文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19132894/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com