您的位置:首页 > 编程语言 > C语言/C++

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的同步了。
阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: