各种输入输出方法的速度比较

duoduo03125

2018-10-16 21:45:33

Personal

因为机房的大佬跟本蒟蒻说scanf+printf的速度比cin+cout在数据规模大于100万时会快很多,所以我决定来测一下。 step 1.用rand()函数生成500万个随机数,保存在test.in中。 step 2.用scanf/cin读入,并用printf/cout输出在test.out中。 step 3.记录结果。 cin+cout:21.94s完毕。 scanf+printf:21.36s完毕。 下面有请**爆炸级BOSS**选手————**快读**出场! 快读+快速输出:2.946s!(**神级操作!!!**) emmmmmmm...... 虽然快读+快速输出快出天际,但是因为快速输出并不常用,所以我们用快读+printf再测试一遍。 快读+printf:17.26s!(时间是快速输出的5倍多!) 综上,scanf+printf对于读入、输出的优化并不是很明显,而快读虽然快了不少,但是如果不配上快速输出,效果也并不令人满意。所以照理来说我们在信(bao)息(li)竞(da)赛(biao)时要把快读和快输都配上,才能成功卡常。 那么问题就来了,为什么打快读的千千万,打快速输出的却没几个呢?其实原因很简单,在平时的OI竞赛中,输出的数据一般数量都很少,这样就没有必要打快速输出了。 最后,附上本次试验的代码。 ``` #include<bits/stdc++.h> using namespace std; int read() //快读 { char ch=getchar(); int res=0; while(ch>'9' || ch<'0') ch=getchar(); while(ch>='0' && ch<='9') { res=res*10+ch-'0'; ch=getchar(); } return res; } void write(int x) //快速输出 { if(x<0) putchar('-'),x=-x; if(x>9) write(x/10); putchar(x%10+'0'); } int main() { int p; freopen("test.in","r",stdin); freopen("test.out","w",stdout); for(int i=1;i<=5000000;i++) { //cin>>p; //scanf("%d",&p); //p=read(); //cout<<p<<" "; //printf("%d ",p); //write(p); //putchar(' ');//快速输出时需手动输出空格 } return 0; } ```