DEV Community

Yilong Wu
Yilong Wu

Posted on • Edited on

C++ I/O Optimization for Competitive Programming — Fast Read, Fast Write, and More

I'm AlanWu. I spent way too long on Luogu wondering why my solution was TLE even though the algorithm was right. Then I learned about I/O.


The two lines that fix 90% of it

ios::sync_with_stdio(false);
cin.tie(nullptr);
Enter fullscreen mode Exit fullscreen mode

Put these at the top of main. That's it. You just made cin about as fast as scanf.

What they do: the first line unties C++ streams from C streams (so they don't sync buffers). The second line unties cin from cout (so cout doesn't flush before every cin). Together, reading 1 million ints drops from ~2 seconds to ~0.3.


endl is a trap

cout << x << endl;   // flushes every time — slow
cout << x << '\n';   // doesn't flush — fast
Enter fullscreen mode Exit fullscreen mode

endl does '\n' AND flush. You almost never need the flush part during a contest. Use '\n'.


When you need even more speed: fast read

For problems with 10^6+ numbers, cin with sync off is still not enough. You need integer parsing by hand:

inline int read() {
    int x = 0, f = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9') {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9') {
        x = x * 10 + (ch - '0');
        ch = getchar();
    }
    return x * f;
}
Enter fullscreen mode Exit fullscreen mode

And a matching fast write:

inline void write(int x) {
    if (x < 0) putchar('-'), x = -x;
    if (x > 9) write(x / 10);
    putchar(x % 10 + '0');
}
Enter fullscreen mode Exit fullscreen mode

Use these when every millisecond counts. Most problems don't need them.


freopen for local testing

Typing test cases by hand is slow. Use file redirection:

#ifdef LOCAL
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
Enter fullscreen mode Exit fullscreen mode

Now cin reads from input.txt and cout writes to output.txt when you compile with -DLOCAL. On the judge, LOCAL isn't defined, so it reads from stdin like normal. You never need to change your code between local testing and submission.


Speed tier summary

Method 1 million ints When to use
cin >> x (no optimization) ~2.0s Never for contests
cin >> x (sync off) ~0.3s Default for most problems
scanf("%d", &x) ~0.3s Same tier as optimized cin
read() (custom) ~0.15s 10^6+ integers, strict time limits

For 90% of competition problems, just the two lines + '\n' is enough.


My GitHub: https://github.com/Cn-Alanwu

Top comments (0)