跳到正文

科技·工程

无聊的输入输出测试

aaron0919约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 4 分钟

版本

  1. v1当前

无聊的输入输出测试

机器

Ubuntu 18.04 LTS amd64 和 C++14 以及均无 O2。

测试

cin 输入 5e5 个六位数。

  1. 无特殊 147ms
  2. cin.tie(0) 131ms
  3. ios_base::sync_with_stdio(0) 46ms
  4. ios::sync_with_stdio(0) 46ms
  5. 2+3 43ms
  6. 2+4 43ms
  7. cin.tie(0)->sync_with_stdio(0) 42ms

cout 输出 5e6 个六位数。

  1. 有 endl 都 >10s
  2. 只有 '\n' 46ms
  3. cout.tie(0) 48ms
  4. ios_base::sync_with_stdio 38ms
  5. ios::sync_with_stdio 39ms
  6. 3+4 39ms
  7. 3+5 37ms
  8. cout.tie(0)->sync_with_stdio(0) 49ms

scanf 输入 5e5 个六位数。

  1. 无特殊 12ms
  2. ios_base::sync_with_stdio 12ms
  3. ios::sync_with_stdio 12ms
  4. cin.tie(0)->sync_with_stdio(0) 15ms

printf 输出 5e6 个六位数。

  1. 无特殊 48ms
  2. ios_base::sync_with_stdio 49ms
  3. ios::sync_with_stdio 49ms
  4. cout.tie(0)->sync_with_stdio(0) 54ms

快读输入 5e5 个六位数(cin/cout 均开满)

C++
inline ll read()
{
    static char ch, last;
    static ll res;
    ch = last = res = 0;
    while (!isdigit(ch))
    {
        last = ch, ch = getchar();
    }
    while (isdigit(ch))
    {
        res = res * 10 + ch - '0', ch = getchar();
    }
    return last == '-' ? -res : res;
}
  1. 如上 6ms
  2. #define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++) 5ms
  3. cin.read(buf, 1 << 20) 6ms

快输输出 5e6 个六位数

C++
char _stk[20];
int _tp = 0;
inline void write(long long x)
{
    do
    {
        _stk[++_tp] = x % 10, x /= 10;
    } while (x);
    while (_tp)
    {
        putchar(_stk[_tp--] | 48);
    }
}
  1. 如上 65ms
  2. fwrite(obuf, O - obuf, 1, stdout) 28ms
  3. cout.write(buf, pout - buf) 30ms

总结

输入:

代码
fread() < cin.read() < read() < scanf() < cin(no tie no sync) < cin(no sync) < cin(no tie) < cin

输出:

代码
fwrite() < cout.write() < cout(no tie no sync no endl) < cout(no sync no endl) < printf() < cout(no tie no endl) < cout(no endl) < write < cout

组合:fread+fwrite < cin.read()+cout.write() < read()+printf() < no sync no tie no endl cin+cout

原文