Comparison of scanf and cin performance and comparison of scanfcin Performance
My lab machine configuration is:
I connected stdin to the input file and tested the data of magnitude 104, 105, 106, and 107 in sequence. The result is as follows.
The bar chart is as follows:
The following table is displayed when the time is 1, 10000:
The time of cin/scanf is as follows:
It can be seen that the time when cin reads the same data is 3.5 ~ of scanf ~ 4 times.
The test code is as follows:
1 #define _CRT_SECURE_NO_WARNINGS 2 #include <iostream> 3 #include <string> 4 #include <ctime> 5 #include <cstdio> 6 using namespace std; 7 const int N = 10000; // modify this to change the size of data 8 int main() 9 {10 clock_t start;11 FILE* ptr = freopen("data.out", "rb", stdin);12 13 start = clock();14 15 16 for (int cnt = 0; cnt < N; cnt++) {17 int tmp;18 // cin >> tmp; // remove the comment symbol to test on cin19 scanf("%d", &tmp);20 }21 22 clock_t end;23 end = clock();24 25 double seconds = (double)(end - start) / CLOCKS_PER_SEC;26 27 printf("%lf\n", seconds);28 29 fclose(stdin);30 return 0;31 }View Code