Vin*_*ent 8 c++ printf ofstream
我正在运行一些基准测试,以找到最有效的方法将大型数组写入C++文件(ASCII中超过1Go).
所以我将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;
}
Run Code Online (Sandbox Code Playgroud)
我的巨大问题是,与std :: ofstream相比,fprintf似乎要慢12倍.您是否知道我的代码中问题的根源是什么?或者也许std :: ofstream与fprintf相比是非常优化的?
(和另一个问题:你知道另一种更快的写文件方式)
非常感谢你
(细节:我用g ++ -Wall -O3编译)