gpt4 book ai didi

c++ - 为什么 ofstream 比 fprintf 慢?

转载 作者:行者123 更新时间:2023-11-30 04:43:50 26 4
gpt4 key购买 nike

更新

@Ruslan 向我指出 Why is snprintf consistently 2x faster than ostringstream for printing a single number?它提供了一个答案和错误报告的链接。

原始问题

我的总体感觉表明使用 C++ ofstream<<运算符应该具有类似的性能,前提是我使用endl但字面意思 "\n"而不是跳过隐式刷新。

此外,this question支持我的想法。

因此,在下面的示例中,我希望运行时大致相似,但在流式传输方面略有优势。

#include <cstdio>
#include <string>
#include <fstream>

#include <boost/timer/timer.hpp>

using namespace std;

const int LOOPS = 10000000;
const double d = 1.231;
const float f = 1.232;
const char *s = "1.233";

void stream_out() {
boost::timer::auto_cpu_timer t;

ofstream out;
out.open("ofstream");
for(int i = 0; i < LOOPS; ++i) {
out << d << "\n";
out << f << "\n";
out << s << "\n";
}
}

void print_out() {
boost::timer::auto_cpu_timer t;

FILE* fout = fopen("fprintf", "w");
for(int i = 0; i < LOOPS; ++i) {
fprintf(fout, "%g\n", d);
fprintf(fout, "%g\n", f);
fprintf(fout, "%s\n", s);
}
}

int main() {
stream_out();
print_out();
return 0;
}

然而,事实并非如此。当使用 g++ 构建并在我的 RHEL7 机器上运行时,它显示:

$ g++ --version
g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-36)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$ g++ -O2 -o test test.cpp -lboost_timer -lboost_system

$ ./test
7.697337s wall, 6.660000s user + 0.160000s system = 6.820000s CPU (88.6%)
4.724694s wall, 4.580000s user + 0.130000s system = 4.710000s CPU (99.7%)

那么,我这里的误解是什么?不应该ofstream因为它不需要在运行时解析格式字符串和可变参数,所以速度会稍微快一点吗?我是否漏掉了一些明显的东西?

恢复到 fprintf() 会很遗憾正是这种性能差异。

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