我正在进行一些基准测试,以找到在C++中将大型数组(超过1Go的ASCII字符)写入文件的最高效方式。 因此,我比较了std :: ofstream与fprintf(请参见我使用的开关)。
我的一个大问题是,相比于std :: ofstream,fprintf似乎要慢12倍以上。你有没有想过这个问题在我的代码中的根源是什么?或者说,与fprintf相比,std :: ofstream非常优化了吗?
(另一个问题:您知道另一种更快的编写文件的方法吗?)
非常感谢。
(详细信息:我正在使用g ++ -Wall -O3进行编译)
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;
}
我的一个大问题是,相比于std :: ofstream,fprintf似乎要慢12倍以上。你有没有想过这个问题在我的代码中的根源是什么?或者说,与fprintf相比,std :: ofstream非常优化了吗?
(另一个问题:您知道另一种更快的编写文件的方法吗?)
非常感谢。
(详细信息:我正在使用g ++ -Wall -O3进行编译)
ostream::write()
:http://www.cplusplus.com/reference/iostream/ostream/write/ - Nim