【发布时间】:2011-10-24 14:53:27
【问题描述】:
我正在运行一些基准测试,以找到将大型数组写入 C++ 文件的最有效方法(超过 1Go 的 ASCII 码)。
所以我比较了 std::ofstream 和 fprintf(见下面我使用的开关)
case 0: {
std::ofstream out(title, std::ios::out | std::ios::trunc);
if (out) {
ok = true;
for (i=0; i<M; i++) {
for (j=0; j<N; j++) {
out<<A[i][j]<<" ";
}
out<<"\n";
}
out.close();
} else {
std::cout<<"Error with file : "<<title<<"\n";
}
break;
}
case 1: {
FILE *out = fopen(title.c_str(), "w");
if (out!=NULL) {
ok = true;
for (i=0; i<M; i++) {
for (j=0; j<N; j++) {
fprintf(out, "%d ", A[i][j]);
}
fprintf(out, "\n");
}
fclose(out);
} else {
std::cout<<"Error with file : "<<title<<"\n";
}
break;
}
我最大的问题是 fprintf 似乎比 std::ofstream 慢了 12 倍以上。您知道我的代码中问题的根源是什么吗?或者可能 std::ofstream 与 fprintf 相比非常优化?
(还有一个问题:你知道另一种更快的写入文件的方法吗)
非常感谢
(详情:我是用 g++ -Wall -O3 编译的)
【问题讨论】:
-
我认为你应该使用 fputs 而不是 fprintf 以获得更多类似的行为
-
也看看
ostream::write():cplusplus.com/reference/iostream/ostream/write -
@AndersK.: 不,fputs 相当于一个streambuf(未格式化); fprintf 是 ostream 的正确对应物。
-
@MSalters 你为什么这么认为? fprintf 包含变量参数列表处理,而 ostream 上的 operator
-
FWIW:This program,源自 OP 的程序片段,运行 switch 语句的任一分支所需的时间基本相同。