今天做题做不进去,就想着学了C的输入输出吧,毕竟我一直使用C++的stream太慢了,一般考数据结构的题都是上百万的数据需要输入输出。记得看到一道题直接注明类似“给使用C++同学的提示:极限数据中使用流将比使用stdio.h中的输入输出函数多花1s时间”。这样学习C的stdio 就显得很必要了。但是今天出现了诡异的问题。

我们看到,慢得出名的stream竟然比C的I/O快?!反复运行都是这个结果,只是程度有所不同……而且不仅仅是这个程序,我把cashier的输入输出改了以后速度也没提高。太诡异了……
下面帖出代码,大家帮忙看看是不是我写得不对 – -
#include <iostream>
#include <fstream>
#include <cstdio>
#include <ctime>
using namespace std;
int main()
{
printf("用C函数输出1000,0000个数花费时间为:");
clock_t b=clock();
FILE *out = fopen("test.txt","w");
for(unsigned i=0;i<10000000;i++) fprintf(out,"%d ",i);
fclose(out);
printf("%dms\n",clock()-b);
cout << "用stream输出1000,0000个数花费时间为:";
clock_t a = clock();
ofstream fout("test.txt");
for(unsigned i=0;i<10000000;i++) fout << i << ' ';
fout.close();
cout << clock()-a << "ms" << endl;
printf("用C函数读入1000,0000个数花费时间为:");
clock_t c = clock();
FILE *in = fopen("test.txt","r");
for(unsigned i=0,j;i<10000000;i++) fscanf(in,"%u ",&j);
fclose(in);
printf("%dms\n",clock()-c);
printf("用stream读入1000,0000个数花费时间为:");
clock_t d = clock();
ifstream fin("test.txt");
for(unsigned i=0,j;i<10000000;i++) fin >> j;
fin.close();
cout << clock()-d << "ms\n";
system("pause");
}
update at 6.17:
下面是我今天(6.17)日在ubuntu下用anjuta&g++做的测试情况。(忘了指明,上面的测试是在winXP下用devc++&g++做的。)
几乎完全一样的代码(结果的显示格式稍做了变化),但结果完全不同。fstream的劣势很明显了。

鱼牛本来的解释是“我们平常说stream慢是指iostream,不是fstream”,看来也不尽然了。
