今天刷題時,在oj上輸入數據時用scanf時AC,然而用cin就TLE,cin的使用,往往更爲方便,但貌似效率比scanf低好多,於是乎測試了一下cin和scanf的效率。
測試代碼如下:
#include <iostream>
#include <time.h>
#include <stdio.h>
#define N 10000
using namespace std;
int main()
{
time_t first, second;
int t;
first=time(NULL);
for(int i=0; i<N; i++)
cin >> t;
second=time(NULL);
printf("Time of test1 is: %fseconds\n",difftime(second,first));
first=time(NULL);
for(int i=0; i<N; i++)
scanf("%d",&t);
second=time(NULL);
printf("Time of test2 is: %fseconds\n",difftime(second,first));
return 0;
}
爲了使測試準確,兩次輸入都是用的相同的數據
tool爲生成數據的一個小程序~~
首先設定N爲10000時,測試了10000個輸入數據,輸出結果如下:
二者幾乎無差別,設定N爲100000,測試結果如下:
當數值加到180000時,結果:
當數據爲1000000時,結果爲:
可見,當輸入小規模數據時cin和scanf之間的差距不是很明顯,但對於大數據,scanf的優勢相當明顯。況且這只是純的讀入測試,而且還是在本地,如果在實際比賽中,cin的效率 會更低,因此,在ACM中,儘量使用scanf來讀取數據,除非數據量已知且不夠大,可用cin。