C++文件I/O比C文件I/O更难.那么在C++中,为文件I/O创建一个新库是否有用?我的意思是<fstream>
任何人都可以告诉我C++文件I/O有什么好处吗?
Dav*_*nch 15
意见
我不知道任何使用C++流的真实项目.它们太慢而且难以使用.有一些较新的库,如FastFormat和Boost版本声称更好,有一篇关于它们的ACCU Overload杂志.我个人在C++中使用过去15年左右的c FILE库,我看不出有任何改变的理由.
速度
这是一个小测试程序(我快速敲一下)来显示基本的速度问题:
#include <stdio.h>
#include <time.h>
#include<iostream>
#include<fstream>
using namespace std;
int main( int argc, const char* argv[] )
{
const int max = 1000000;
const char* teststr = "example";
int start = time(0);
FILE* file = fopen( "example1", "w" );
for( int i = 0; i < max; i++ )
{
fprintf( file, "%s:%d\n", teststr, i );
}
fclose( file );
int end = time(0);
printf( "C FILE: %ds\n", end-start );
start = time(0);
ofstream outdata;
outdata.open("example2.dat");
for( int i = 0; i < max; i++ )
{
outdata << teststr << ":" << i << endl;
}
outdata.close();
end = time(0);
printf( "C++ Streams: %ds\n", end-start );
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的电脑上的结果:
C FILE: 5s
C++ Streams: 260s
Process returned 0 (0x0) execution time : 265.282 s
Press any key to continue.
Run Code Online (Sandbox Code Playgroud)
正如我们所看到的,这个简单的例子慢了52倍.我希望有办法让它更快!
注意:在我的示例中将endl更改为'\n'改进了C++流,使其仅比FILE*流慢3倍(感谢jalf)可能有更快的方法.
难以使用
我不能说printf()不简洁,但是一旦你超过宏代码的初始WTF,它就更灵活(IMO)并且更容易理解.
double pi = 3.14285714;
cout << "pi = " << setprecision(5) << pi << '\n';
printf( "%.5f\n", pi );
cout << "pi = " << fixed << showpos << setprecision(3) << pi << '\n';
printf( "%+.3f\n", pi );
cout << "pi = " << scientific << noshowpos << pi<< '\n';
printf( "%e\n", pi );
Run Code Online (Sandbox Code Playgroud)
问题
是的,可能需要一个更好的C++库,很多是FastFormat就是那个库,只有时间会证明.
戴夫
请看看
http://www.ddj.com/cpp/184403651
那么你会比CI/O更喜欢C++ I/O.
简而言之,如果您知道读取或写入之前的数据大小以及速度,则首选C. 如果您不知道数据大小和有效代码,则首选C++.
为了回应David Allan Finch的回答,我在他的基准测试代码中修复了一个错误(他在每一行之后刷新了C++版本的流),并重新测试:
C++循环现在看起来像这样:
start = time(0);
{
ofstream outdata("example2.txt");
for( int i = 0; i < max; i++ )
{
outdata << teststr << ":" << i << "\n"; // note, \n instead of endl
}
}
end = time(0);
Run Code Online (Sandbox Code Playgroud)
我运行10000000次迭代(比原始代码多10倍,因为否则,数字对于time()的糟糕分辨率太小而无法给我们任何有意义的东西))并且输出为:
G++ 4.1.2:
C FILE: 4s
C++ Streams: 6s
MSVC9.0:
C FILE: 10s
C++ Streams: 23s
Run Code Online (Sandbox Code Playgroud)
(注意,MSVC版本在我的笔记本电脑上运行,硬盘速度明显变慢)
但这给我们的性能差异为1.5-2.3x,具体取决于实现方式.和其他外部因素.
归档时间: |
|
查看次数: |
10029 次 |
最近记录: |