cin,cout,printf,scanf效率对比

From:http://www.cnblogs.com/killerlegend/p/3918452.html

Author:KillerLegend

Date:2014.8.17

杭电OJ之3233很简单的一个问题,谁知道一直提示我超时,超时,最后都快哭了,C++代码如下:

#include <iostream>

#include <iomanip>

using namespace std;

int main()

{

int t,tmp,band,index=0;

while(cin>>t>>tmp>>band)

{

if(t==0||tmp==0||band==0) break;

double a,b,sum=0.0;

for(int i=0;i<t;++i)

{

cin>>a>>b;

sum+=a*(100-b)*0.01;

}

cout<<"Case "<<++index<<": "<<fixed<<setprecision(2)<<sum/band<<endl<<endl;

}

return 0;

}
后来...将输入输出流换成了scanf和printf,结果就神奇的AC了...

#include <cstdio>

int main()

{

int t,tmp,band,index=0;

while(scanf("%d%d%d",&t,&tmp,&band))

{

if(t==0||tmp==0||band==0) break;

double a,b,sum=0.0;

for(int i=0;i<t;++i)

{

scanf("%lf%lf",&a,&b);

sum+=a*(100-b)*0.01;

}

printf("Case %d: %.2f\n\n",++index,sum/band);

}

return 0;

}
这真是太让人伤心了...所以我打算测试一下cin和scanf,cout和printf:

cout测试:

#include <iostream>

#include <cstdio>

#include <time.h>

using namespace std;

int main()

{

freopen("in.conf","r",stdin);

freopen("out.conf","w",stdout);

clock_t t1,t2,t3,t4;

t1 = clock();

for(int i=0;i<10000000;++i)cout<<i<<" ";

t2 = clock();

cout<<"cin-time:"<<(double)(t2-t1)/CLOCKS_PER_SEC<<endl;

return 0;

}
结果:5.206s

printf测试:

#include <iostream>

#include <cstdio>

#include <time.h>

using namespace std;

int main()

{

freopen("in.conf","r",stdin);

freopen("out.conf","w",stdout);

clock_t t1,t2,t3,t4;

t1 = clock();

for(int i=0;i<10000000;++i)printf("%d ",i);

t2 = clock();

cout<<"cin-time:"<<(double)(t2-t1)/CLOCKS_PER_SEC<<endl;

return 0;

}
结果:6.202s

我们使用上面循环1千万次所产生的数据(78.89MB),用于下面读入时的测试数据:

使用cin读入:

#include <iostream>

#include <cstdio>

#include <time.h>

using namespace std;

int main()

{

freopen("out.conf","r",stdin);

freopen("in.conf","w",stdout);

clock_t t1,t2,t3,t4;

t1 = clock();

int k;

for(int i=0;i<10000000;++i)cin>>k;

t2 = clock();

cout<<"cin-time:"<<(double)(t2-t1)/CLOCKS_PER_SEC<<endl;

return 0;

}
结果是38.507s

使用scanf读入:

#include <iostream>

#include <cstdio>

#include <time.h>

using namespace std;

int main()

{

freopen("out.conf","r",stdin);

freopen("in.conf","w",stdout);

clock_t t1,t2,t3,t4;

t1 = clock();

int k;

for(int i=0;i<10000000;++i)scanf("%d",&k);

t2 = clock();

cout<<"cin-time:"<<(double)(t2-t1)/CLOCKS_PER_SEC<<endl;

return 0;

}
结果是4.204s

结果一览表:

1

 

结论:输出时尽量使用cout,输入时尽量使用scanf.

posted @ 2014-08-17 22:51  KillerLegend  Views(2177)  Comments(0Edit  收藏  举报