C++ 里利用 std::ios::sync_with_stdio(false) 解决TLE问题
2018-08-04 08:42
399 查看
关于用C++里面的cin读取数据,我们都知道它的速度相对于C里面的scanf是比较慢的。。。
首先,我随机生成了10000000个整数
[code]#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进行读取,计算读取的时间
[code]#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里面编译运行的,
[code]#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)
[code]#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,速度明显加快了不少。
[code]cin慢是有原因的,其实默认的时候,cin与stdin总是保持同步的,也就是说这两种 方法可以混用,而不必担心文件指针混乱,同时cout和stdout也一样,两者混 用不会输出顺序错乱。正因为这个兼容性的特性,导致cin有许多额外的开销, 如何禁用这个特性呢?只需一个语句std::ios::sync_with_stdio(false); 这样就可以取消cin于stdin的同步了。阅读更多
相关文章推荐
- C++ 里利用 std::ios::sync_with_stdio(false) 解决TLE问题
- 转载——探寻C++最快的读取文件的方案std::ios::sync_with_stdio(false)——转载
- std::ios::sync_with_stdio(false);--------探寻C++最快的读取文件的方案
- 探寻C++最快的读取文件的方案std::ios::sync_with_stdio(false) (转)
- 关于std::ios::sync_with_stdio(false);
- std::ios::sync_with_stdio(false); cin.tie(0);
- std:ios::sync_with_stdio(false);
- 关于ios::sync_with_stdio(false);和 cin.tie(0)加速c++输入输出流
- 读入外挂 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);
- 关于ios::sync_with_stdio(false);和 cin.tie(0)加速c++输入输出流
- C,C++,C++中添加ios::sync_with_stdio(false);代码大小和耗时测评
- YT14-HDU-找循环节 (关于std::ios::sync_with_stdio(false);的作用和疑问)
- std::ios::sync_with_stdio(false);
- std::ios::sync_with_stdio(false);
- ios_base::sync_with_stdio(false)可以来打消iostream的输入输出缓存,可以节省许多时间,使效率与scanf与printf相差无几
- [置顶] ios::sync_with_stdio(false) 详细解释
- ios::sync_with_stdio(false) 改变C++流输入输出的速度