scanf和cin性能的比较
我的实验机器配置是:
- 处理器:Intel(R) Core(TM) i3-7100U CPU @ 2.40GHz 2.40GHz
- 随机访问存储器:4.00GB
- 操作系统:Windows10
- 集成开发环境:Visual Studio 2017
我将stdin与输入文件链接在一起,依次在104、105、106、107量级的数据上进行测试,得到结果如下。

画成柱状图如下:
以10000数量级的时间为1,可得到这样的表格:

cin/scanf的时间比如下:

由此可见,cin读入相同数据的时间是scanf的3.5~4倍。
测试代码如下:
 
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 cin 19 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 }
 
                    
                 
 
                
            
         
 浙公网安备 33010602011771号
浙公网安备 33010602011771号