C++ 里利用 std::ios::sync_with_stdio(false) 解决TLE问题
2018-01-23 10:06
591 查看
2018-1-23
关于用C++里面的cin读取数据,我们都知道它的速度相对于C里面的scanf是比较慢的。。。
首先,我随机生成了10000000个整数
然后我们用scanf进行读取,计算读取的时间
结果为1.782,这是在windows下的Dev里面编译运行的,
这种情况下的结果为9.701,我们加上std::ios::sync_with_stdio(false)
变成了2.166,速度明显加快了不少。
关于用C++里面的cin读取数据,我们都知道它的速度相对于C里面的scanf是比较慢的。。。
首先,我随机生成了10000000个整数
#include<stdio.h> #include<stdlib.h> int main(){ FILE *f=fopen("data.txt","w"); for (int i=0;i<10000000;i++){ fprintf (f,"%d ",rand()); } return 0; }
然后我们用scanf进行读取,计算读取的时间
#include<stdio.h> #include<stdlib.h> #include<time.h> int main(){ int start=clock(); FILE *f=freopen("data.txt","r",stdin); for (int i=0;i<10000000;i++){ int t; scanf("%d",&t); } printf("%.3lf\n",double(clock()-start)/CLOCKS_PER_SEC); retun 0; }
结果为1.782,这是在windows下的Dev里面编译运行的,
#include<iostream> #include<stdio.h> #include<stdlib.h> #include<time.h> using namespace std; int main(){ int start=clock(); FILE *f=freopen("data.txt","r",stdin); for (int i=0;i<10000000;i++){ int t; std::cin>>t; } printf("%.3lf\n",double(clock()-start)/CLOCKS_PER_SEC); return 0; }
这种情况下的结果为9.701,我们加上std::ios::sync_with_stdio(false)
#include<iostream> #include<stdio.h> #include<stdlib.h> #include<time.h> using namespace std; int main(){ int start=clock(); FILE *f=freopen("data.txt","r",stdin); std::ios::sync_with_stdio(false); for (int i=0;i<10000000;i++){ int t; std::cin>>t; } printf("%.3lf\n",double(clock()-start)/CLOCKS_PER_SEC); return 0; }
变成了2.166,速度明显加快了不少。
cin慢是有原因的,其实默认的时候,cin与stdin总是保持同步的,也就是说这两种 方法可以混用,而不必担心文件指针混乱,同时cout和stdout也一样,两者混 用不会输出顺序错乱。正因为这个兼容性的特性,导致cin有许多额外的开销, 如何禁用这个特性呢?只需一个语句std::ios::sync_with_stdio(false); 这样就可以取消cin于stdin的同步了。
相关文章推荐
- std::ios::sync_with_stdio(false);--------探寻C++最快的读取文件的方案
- 转载——探寻C++最快的读取文件的方案std::ios::sync_with_stdio(false)——转载
- 探寻C++最快的读取文件的方案std::ios::sync_with_stdio(false) (转)
- 关于ios::sync_with_stdio(false);和 cin.tie(0)加速c++输入输出流
- 关于std::ios::sync_with_stdio(false);
- C,C++,C++中添加ios::sync_with_stdio(false);代码大小和耗时测评
- std::ios::sync_with_stdio(false);
- std::ios::sync_with_stdio(false); cin.tie(0);
- 关于ios::sync_with_stdio(false);和 cin.tie(0)加速c++输入输出流
- std::ios::sync_with_stdio(false);
- std:ios::sync_with_stdio(false);
- 读入外挂 std::ios::sync_with_stdio(false);
- 关于ios::sync_with_stdio(false);和 cin.tie(0)加速c++输入输出流
- 杭电ACM 找循环节 std::ios::sync_with_stdio(false);
- std::ios::sync_with_stdio(false);
- YT14-HDU-找循环节 (关于std::ios::sync_with_stdio(false);的作用和疑问)
- [ ios::sync_with_stdio(false);](http://blog.csdn.net/yujuan_mao/article/details/8119529)
- ios::sync_with_stdio(false);
- iOS \'The sandbox is not sync with the Podfile.lock\'问题解决
- ios::sync_with_stdio(false);