cin,cout,printf,scanf效率對比

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

Author:KillerLegendios

Date:2014.8.17測試

杭電OJ之3233很簡單的一個問題,誰知道一直提示我超時,超時,最後都快哭了,C++代碼以下:spa

#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測試:code

#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測試:htm

#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),用於下面讀入時的測試數據:blog

使用cin讀入:ip

#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讀入:ci

#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

結果一覽表:get

1

 

結論:輸出時儘可能使用cout,輸入時儘可能使用scanf.

相關文章
相關標籤/搜索