通过插入运算符 '<<' 执行写入时使用 std::stringbuf 进行缓冲的效果
Effect of using std::stringbuf for buffering while performing a write via insertion operator '<<'
我正在尝试对手动缓冲(通过 std::stringbuf
)对 运行 时间的影响进行基准测试,同时执行对文件的写入,而不是插入运算符 [=14] 完成的缓冲=].
版本 1(无手动缓冲)
此版本涉及在每次迭代时执行写入。
std::ofstream ofs;
ofs.open("output_file", std::ios::out);
for (int i = 0; i < 100000000; i++)
ofs << "Hello world!\n";
时间: 2.83s 用户 1.14s 系统 28% cpu 13.918 总计
版本 2(带手动缓冲)
此版本在最终写入之前缓冲 std::string
对象中的全部数据。
std::string buffer;
std::ofstream ofs;
ofs.open("output_file", std::ios::out);
for (int i = 0; i < 100000000; i++)
buffer.append("Hello world!\n");
ofs << buffer;
时间: 1.87s 用户 2.27s 系统 24% cpu 总计 16.654
版本 1 和版本 2 的 运行 时间之间存在明显差异,并且在不同的运行中观察到类似的行为。当第二个版本仅执行单个写入操作而不是第一个版本中的多个写入操作时,为什么第二个版本最终会变慢?
此结果也与 previous question 中发布的结果形成对比,但当前情况略有不同。
没有"only perform a single write operation";您没有考虑构建该字符串的成本,该字符串不为零。
您可能会发现 buffer.reserve(100000000 * strlen("Hello world!\n"))
有点帮助。
我正在尝试对手动缓冲(通过 std::stringbuf
)对 运行 时间的影响进行基准测试,同时执行对文件的写入,而不是插入运算符 [=14] 完成的缓冲=].
版本 1(无手动缓冲)
此版本涉及在每次迭代时执行写入。
std::ofstream ofs;
ofs.open("output_file", std::ios::out);
for (int i = 0; i < 100000000; i++)
ofs << "Hello world!\n";
时间: 2.83s 用户 1.14s 系统 28% cpu 13.918 总计
版本 2(带手动缓冲)
此版本在最终写入之前缓冲 std::string
对象中的全部数据。
std::string buffer;
std::ofstream ofs;
ofs.open("output_file", std::ios::out);
for (int i = 0; i < 100000000; i++)
buffer.append("Hello world!\n");
ofs << buffer;
时间: 1.87s 用户 2.27s 系统 24% cpu 总计 16.654
版本 1 和版本 2 的 运行 时间之间存在明显差异,并且在不同的运行中观察到类似的行为。当第二个版本仅执行单个写入操作而不是第一个版本中的多个写入操作时,为什么第二个版本最终会变慢?
此结果也与 previous question 中发布的结果形成对比,但当前情况略有不同。
没有"only perform a single write operation";您没有考虑构建该字符串的成本,该字符串不为零。
您可能会发现 buffer.reserve(100000000 * strlen("Hello world!\n"))
有点帮助。