玄学 - 快速读入Benchmark
主流的几种提高读入效率的方法:
ios::sync_with_stdio(false)效果拔群cin.tie(nullptr)收效甚微setvbuf(stdin, buffer, _IOLBF, sizeof(buffer))有效果scanf有效果getchar未测试
测试环境
读入一个 128M 的整数大文件,有 1«26 个 1。
使用 tmpfs 降低磁盘干扰。
测试代码
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
#include <iostream>
using namespace std;
#ifdef CIN
#   define readint(_x) { cin >> _x; }
#else
#   define readint(_x) { scanf("%d", &_x); }
#endif
char bbuf[1<<22]; // 2MB
int main() {
    #ifdef SETVBUF
    setvbuf(stdin, bbuf, _IOLBF, sizeof(bbuf));
    #endif
    #ifdef ASYNC
    ios::sync_with_stdio(false);
    #endif
    #ifdef TIE
    cin.tie(nullptr);
    #endif
    for(int i=0;i<1<<26;i++) {
        int x;
        readint(x);
    }
    cout << clock() << endl;
}
这组代码上跑得最快的是这组编译开关:
1
g++ test.cpp -DASYNC -DCIN -DTIE -DSETVBUF # 上文 1 + 2 + 3