read

在做多校时就看过这些代码,一直没有放在心上,现在心血来潮,测试了一下它的实用性。
我们知道,cin最慢,scanf较快,然而字符串读入的getchar是最快的。那么到底有多块呢?‘

测试

博主自己模拟了1+1000*10000的数据来整型读入。光是数据文件就有
test.in
然后用scanf和read来比较一下。cin我已经放弃了…………

结果

scanf

scanf千万级读入

read

read千万级读入

总结

快速读read快scanf 4倍,时间为scanf的1/4,在ACM的大数据题目中可以节约不少时间……

c++代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <time.h>
using namespace std;
#define showtime printf("time = %.15f\n",clock() / (double)CLOCKS_PER_SEC)
int dp[100800];
inline int read(){//快速读入是邪教
char c;
int ret = 0;
int sgn = 1;
do{c = getchar();}while((c < '0' || c > '9') && c != '-');
if(c == '-') sgn = -1; else ret = c - '0';
while((c = getchar()) >= '0' && c <= '9') ret = ret * 10 + (c - '0');
return sgn * ret;
}
int main(){
freopen("test.in","r",stdin);
puts("start");showtime;
int t;t=read();
for(;t--;){
for(int i=1; i<=10000 ; i++){
dp[i]=read();
}
}
puts("end");showtime;
/*cout<<1000<<endl;
for(int j=1; j<=1000; j++)
for(int i=1; i<=10000 ;i++)
printf("%d%c",i,i==10000?'\n':' ');*/
return 0;
}