很早就知道,c的scanf(printf)比c++的快。刷題時尤其明顯,在這上面超時是常有的事兒。
但,這是別人告訴我的,c快。
為什么快?
從網上借鑒一個例子做個簡單測試:
1.cpp //向一個文件里輸入1000000個隨機數
#include<iostream> #include<fstream> #include<cstdlib> using namespace std; const int num=1000000; int main() { ofstream file("data"); for(int i=0;i<num;i++) { file<<rand()<<' '; if((i+1)%20==0) file<<endl; } return 0; }
2.cpp //用cin讀取這1000000個隨機數
#include<iostream> #include<ctime> #include<cstdio> #include<windows.h> using namespace std; const int num=1000000; int main() { freopen("data","r",stdin); int i,n,start,end; start=clock(); for(i=0;i<num-2;i++) cin>>n; end=clock(); cout<<double(end-start)/CLOCKS_PER_SEC<<endl; Sleep(5000); system("pause"); return 0; }
結果: 耗時 5.281秒
3.cpp //用scanf讀取這1000000個數
#include<ctime> #include<cstdio> #include<stdlib.h> #include<windows.h> #include<iostream> using namespace std; const int num=1000000; int main() { freopen("data","r",stdin); int i,n,start,end; start=clock(); for(i=0;i<num;i++) scanf("%d",&n); end=clock(); //cout<<double(end-start)/CLOCKS_PER_SEC<<endl; printf("%f\n",double(end-start)/CLOCKS_PER_SEC); system("pause"); Sleep(5000); return 0; }
結果: 耗時 0.437秒
結論:scanf真的比cin快。竟快10倍。
運行環境,xp,DEV-C++。
比較合理的解釋:默認情況,cin與stdin總是保持同步的,也就是說這兩種方法可以混用,而不必擔心文件指針混亂,同時cout和stdout也一樣,兩者混用不會輸 出順序錯亂。正因為這個兼容性的特性,導致cin有許多額外的開銷,如何禁用這個特性呢?只需一個語句 std::ios::sync_with_stdio(false);,這樣就可以取消cin於stdin的同步了,此時的cin就與scanf差不多 了。
另一種解釋: cout在輸出時總是要先將輸出的存入緩存區。而printf直接調用系統進行IO,它是非緩存的。所以cout比printf慢。(這種解釋,我沒有驗證)