此篇blog比较了OI里常用四种读入方式
代码实现和计时
0. 数据生成器
(code):
#include<cstdio>
#include<cstdlib>
#include<windows.h>
#define Re register
using namespace std;
const int N=1919810;
int main(){
freopen("sample.txt","w",stdout);
srand(GetTickCount());
for(Re int i=1;i<=N;++i)
printf("%d ",rand()-16374);
}
1. 普通快读
(code):
//1919810个数据约210ms
#include<cstdio>
#include<windows.h>
#define Re register
using namespace std;
inline int read(){
Re int x=0,f=1;
Re char c;
while((c=getchar()) && (c<'0' || c>'9'))
if(c=='-')
f=(int)0xFFFFFFFF;
do
x=(x<<3)+(x<<1)+(c^48);
while((c=getchar()) && c>='0' && c<='9');
return x*f;
}
const int N=1919810;
long Tick1,Tick2;
int main(){
freopen("sample.txt","r",stdin);
Tick1=GetTickCount();
for(int i=1;i<=N;++i)
read();
Tick2=GetTickCount();
printf("%ld",Tick2-Tick1);
}
2. scanf()
(code):
//1919810个数据约670ms
#include<cstdio>
#include<windows.h>
using namespace std;
const int N=1919810;
int n;
long Tick1,Tick2;
int main(){
freopen("sample.txt","r",stdin);
Tick1=GetTickCount();
for(int i=1;i<=N;++i)
scanf("%d",&n);
Tick2=GetTickCount();
printf("%ld",Tick2-Tick1);
}
3. 普通cin>>
(code):
//1919810个数据约1.3s
#include<iostream>
#include<cstdio>
#include<windows.h>
using namespace std;
const int N=1919810;
int n;
long Tick1,Tick2;
int main(){
freopen("sample.txt","r",stdin);
Tick1=GetTickCount();
for(int i=1;i<=N;++i)
cin>>n;
Tick2=GetTickCount();
cout<<Tick2-Tick1;
}
4. cin>>
+ ios::sync_with_stdio(false)
(code):
//1919810个数据约250ms
#include<iostream>
#include<cstdio>
#include<windows.h>
using namespace std;
const int N=1919810;
int n;
long Tick1,Tick2;
int main(){
freopen("sample.txt","r",stdin);
ios::sync_with_stdio(false);
Tick1=GetTickCount();
for(int i=1;i<=N;++i)
cin>>n;
Tick2=GetTickCount();
cout<<Tick2-Tick1;
}
结论
- 普通快读略快于优化
cin>>
- 如果懒得写快读就写优化
cin>>
即可