跳到正文

个人记录

简易快读

Talaodi约 3 分钟
原文
文章信息与版本

文章信息

发布
2023年7月5日
收录
2026年1月23日
更新
2026年11月14日
篇幅
约 3 分钟

版本

  1. v1当前

本文采用 LOJ #7 作为测试。由于 LOJ 上有奇怪的 100ms100ms 的波动,会取连续的 55 次提交的平均数进行参考。标准:ISO C++11,优化:-O2。

普通快读:

C++
void read(ll &x) {
    x = 0;
    char c = getchar();

    while (!isdigit(c)) {
        c = getchar();
    }

    while (isdigit(c)) {
        x = 10 * x + c - '0';
        c = getchar();
    }
}

速度:503,592,503,573,503503,592,503,573,503。平均:534.8534.8。

常见的 fread 快读:

C++
char buf[1 << 22], *p, *q;

inline char getc() {
    return p == q && (q = (p = buf) + fread(buf, 1, 1 << 21, stdin)), p == q ? EOF : *p++;
}

void read(ll &x) {
    x = 0;
    char c = getc();

    while (!isdigit(c)) {
        c = getc();
    }

    while (isdigit(c)) {
        x = 10 * x + c - '0';
        c = getc();
    }
}

速度:446,445,347,322,446446,445,347,322,446。平均:401.2401.2。

实际上只需要把普通快读的 getchar 换成 getchar_unlocked 就会快很多。

C++
void read(ll &x) {
    x = 0;
    char c = getchar_unlocked();

    while (!isdigit(c)) {
        c = getchar_unlocked();
    }

    while (isdigit(c)) {
        x = 10 * x + c - '0';
        c = getchar_unlocked();
    }
}

速度:378,280,286,274,388378,280,286,274,388。平均:321.2321.2。

原理:getchar 为了保证线程安全,在每次使用前和使用后都进行了上锁和解锁的操作,而 getchar_unlocked 没有这些操作,同时它也线程不安全。然而 OI 中根本不用考虑什么线程安全对吧!

优点:好写,速度快。

缺点:Windows 用不了(意味着 CF 用不了)。当然 NOI Linux 能用就行!

注:在 Windows 中可用 _getchar_nolock 代替。

原文