一, 生成测试数据
先把 1000 万个测试数据写入 data.txt 中
- #include <iostream>
- #include <fstream>
- #include <ctime>
- using namespace std;
- const int num=10000000;
- int main()
- {
- ofstream fout("data.txt");
- clock_t t1, t2;
- t1 = clock();
- for(int i = 0; i <num; i++)
- {
- fout << i << ' ';
- }
- t2 = clock();
- cout << "Running time:" << t2 - t1 << "ms" << endl;
- return 0;
- }
运行结果:
4764 ms
电脑的配置为 i7 处理器, 16G 内存, 运行时间接近 5 秒, 生成的 data.txt 文件大小为 77040k, 即 77M 左右.
二, cin 与 printf 的效率比较
- (一)cin
- #include<iostream>
- #include<ctime>
- #include<cstdio>
- using namespace std;
- const int num=10000000;
- int main()
- {
- freopen("data.txt", "r", stdin);
- int i, x;
- clock_t t1, t2;
- t1 = clock();
- for(i = 0; i <num;i++)
- {
- cin>> x;
- }
- t2 = clock();
- cout <<"Running time:" << t2 - t1 << "ms" << endl;
- return 0;
- }
运行结果:
Running time: 16252 ms
分析:
1 先要把测试数据文件 data.txt 拷贝到当前工程目录下
2 stdin 是 C 语言的标准输入流, 表示先把 data.txt 中的数据读取到标准输入流里面, 然后用 cin>> x 的时候, 就不会要求用户从控制台输入数据, 而是从 stdin 中读取数据
(二)printf
三, sync_
四, cout 与 printf 的效率比较
五, 结论
来源: http://www.jianshu.com/p/db22e8cbddea