【测评】各种读入方式的效率

关于OI怎么写快读,什么时候写快读,快读怎么写,一直是一个问题。所以今天测试了一发,看看究竟哪种读入方式更好。

数据生成器

搞来1e7个整数

#include <cstdlib>
#include <cstdio>
 
int main() {
    FILE *out[6];
    out[1] = fopen("data1.txt", "w");
    out[2] = fopen("data2.txt", "w");
    out[3] = fopen("data3.txt", "w");
    out[4] = fopen("data4.txt", "w");
    out[5] = fopen("data5.txt", "w");
    for (int i = 1; i <= 1e7; i++) {
        int x = rand();
        for (int j = 1; j <= 5; j++) fprintf(out[j], "%d\n", x);
    }
    return 0;
}

然后拷贝了$5$份进行测试

读入方式

接下来是不同种读入的代码

#include <bits/stdc++.h>

using namespace std;

char rbuf[1 << 20]; char *p1 = rbuf, *p2 = rbuf;

char gc() {
    if (p1 == p2) {
        p1 = rbuf;
        p2 = rbuf + fread(rbuf, 1, 1 << 20, stdin);
    }
    return p1 == p2 ? EOF : *p1++;
}

int read() {
    register int f = 1, x = 0; register char ch = gc();
    while (!isdigit(ch)) f = (ch == '-' ? -1 : 1), ch = gc();
    while (isdigit(ch)) x = x * 10 + (ch ^ 48), ch = gc();
    return f * x;
}

int qread() {
    register int f = 1, x = 0; register char ch = gc();
    while (!isdigit(ch)) f = (ch == '-' ? -1 : 1), ch = gc();
    while (isdigit(ch)) x = x * 10 + (ch ^ 48), ch = gc();
    return f * x;
}

double Getchar() {
    double s = clock();
    for (int i = 1, x; i <= 1e7; i++) x = qread();
    double t = clock();
    return t - s;
}

double Fread() {
    double s = clock();
    for (int i = 1, x; i <= 1e7; i++) x = read();
    double t = clock();
    return t - s;
}

double Scanf() {
    double s = clock();
    for (int i = 1, x; i <= 1e7; i++) scanf("%d", &x);
    double t = clock();
    return t - s;
}

double Cin() {
    double s = clock();
    for (int i = 1, x; i <= 1e7; i++) cin >> x;
    double t = clock();
    return t - s;
}

double FastCin() {
    ios :: sync_with_stdio(false); cin.tie(NULL);
    double s = clock();
    for (int i = 1, x; i <= 1e7; i++) cin >> x;
    double t = clock();
    return t - s;
}

int main() {
    freopen("data1.txt", "r", stdin);
    freopen("res.txt", "w", stdout);
    printf("getchar: %lf\n", Getchar());
    freopen("data2.txt", "r", stdin);
    printf("fread: %lf\n", Fread());
    freopen("data3.txt", "r", stdin);
    printf("scanf: %lf\n", Scanf());
    freopen("data4.txt", "r", stdin);
    printf("cin: %lf\n", Cin());
    freopen("data5.txt", "r", stdin);
    printf("fastcin: %lf\n", FastCin());
    return 0;
}

测试结果

学校机房电脑,不是很稳。

第一次测试

getchar: 682.000000
fread: 620.000000
scanf: 3906.000000
cin: 9483.000000
fastcin: 2640.000000

第二次测试

getchar: 2185.000000
fread: 589.000000
scanf: 4450.000000
cin: 9854.000000
fastcin: 2161.000000

第三次测试

getchar: 664.000000
fread: 649.000000
scanf: 4020.000000
cin: 7755.000000
fastcin: 2125.000000

跑3e7

getchar: 40577.000000
fread: 26050.000000
scanf: 33746.000000
cin: 46334.000000
fastcin: 49743.000000