A C++ tool reads and prints millions of lines slowly; what do std::ios::sync_with_stdio(false) and std::cin.tie(nullptr) change, and what can they break?
answer
- two layers of buffering
- C and C++ streams kept in step
- input flushes the tied output
- call it before any I/O
- mixing printf afterwards is unsafe
basics
~20 ssync_with_stdio(false) lets the C++ standard streams buffer independently of C stdio, and cin.tie(nullptr) stops std::cin flushing std::cout before every read. Both speed up heavy I/O, but afterwards mixing printf with cout can reorder output and prompts may not appear.
solid answer
~40 sBy default the C++ standard streams are **synchronised** with C's `stdin`/`stdout`/`stderr`: characters behave as if each insertion went straight through the C stream, so `printf` and `std::cout` output interleave in program order. libstdc++'s manual says it achieves this by doing very little buffering in the standard streams. `std::ios::sync_with_stdio(false)` allows the C++ streams to operate independently, with their own buffers. Separately, `std::cin` is **tied** to `std::cout`, so before reading it flushes `std::cout`; in a read-one-print-one loop that is a flush per line. `std::cin.tie(nullptr)` removes that. Costs: call `sync_with_stdio` before any I/O (afterwards the effect is implementation-defined); never mix `printf`/`scanf` with the C++ streams afterwards; prompts without a flush may not show before input; and the standard guarantees freedom from data races for concurrent use of a standard stream object only while it is synchronised.
code
cpp · 10 lines#include <iostream>
int main() {
std::ios::sync_with_stdio(false); // before any I/O on the standard streams
std::cin.tie(nullptr); // reading no longer flushes std::cout
int n;
while (std::cin >> n) std::cout << n * 2 << '\n';
// From here on, do not mix printf or scanf with std::cin / std::cout.
}go deeper
Recall that these two lines speed up heavy C++ stream I/O and must come before any input or output.
Explain synchronisation with C stdio and the cin-cout tie as two separate mechanisms that each cost throughput.
Diagnose slow I/O, apply the calls only where C stdio is not mixed in, and account for prompts, ordering and multi-threaded output.
Set the rule for which binaries may unsynchronise their streams, given third-party code that prints with C stdio and threaded logging.
## Two independent knobs The two calls are often pasted together, but they change different things: | Call | What it changes | Default | |---|---|---| | `std::ios::sync_with_stdio(false)` | lets `std::cin`, `std::cout`, `std::cerr`, `std::clog` buffer independently of C's `stdin`, `stdout`, `stderr` | synchronised | | `std::cin.tie(nullptr)` | stops `std::cin` from flushing `std::cout` before each input operation | `std::cin.tie()` returns `&std::cout` | `sync_with_stdio` is a **static** member of `std::ios_base`, so it affects all eight standard stream objects at once, narrow and wide. `tie` is per stream. ## Synchronisation with C stdio The standard defines a synchronised stream by equivalence. Inserting a character through `std::cout.rdbuf()->sputc(c)` must have the same effect as `fputc(c, stdout)`, and the same for reading and pushing back. That is what lets this work in program order: ```cpp std::cout << "Hel"; std::printf("lo, worl"); std::cout << "d!\n"; ``` How a library meets the rule is its own choice. libstdc++'s manual describes its synchronised standard streams as doing very little buffering of their own, leaving buffering to the C library, and says that once synchronisation is turned off they buffer on their own. Other libraries organise this differently, so the size of the gain varies: on libc++ in one measurement, writing three million numbers to a redirected `std::cout` ran about three times faster with synchronisation off, while reading integers alone showed no measurable difference. ## The tie between cin and cout Before any input operation, a stream's sentry calls `tie()->flush()` if `tie()` is not null. The standard allows skipping the flush when there is nothing buffered, or deferring it until the input buffer actually needs refilling. The purpose is interactive: a prompt such as `Enter a number: ` must be visible before the program blocks for input. In a loop that reads a number and prints a result, the tie means a flush between reads, so buffering is defeated on the output side. In the same libc++ measurement, a read-one-write-one loop over a million integers redirected to a file dropped from about 2.3 seconds to about 0.9 seconds with `std::cin.tie(nullptr)`. ## What the calls break 1. **Order of C and C++ output.** After `sync_with_stdio(false)`, `printf` and `std::cout` each have their own buffer, so their output can appear out of order. The same goes for `std::print` in C++23, which writes to C's `stdout`. Pick one family per program. 2. **Mixing input families.** `scanf` and `std::cin` reading the same input can each buffer ahead and steal characters from the other. 3. **Calling it late.** If any input or output has already happened on the standard streams, the effect of `sync_with_stdio` is implementation-defined. Call it first thing in `main`, before anything prints. 4. **Prompts.** With the tie removed, a prompt written without a flush may still sit in `std::cout`'s buffer while the program waits for input. Interactive tools should flush prompts explicitly or keep the tie. 5. **Threads.** The standard's guarantee that concurrent use of a standard stream object causes no data race is stated for **synchronised** streams. After `sync_with_stdio(false)`, writing to `std::cout` from several threads without your own lock is not covered by that guarantee. 6. **Crash diagnostics.** More buffering means more output lost if the process dies; `std::cerr` stays unit-buffered, so put diagnostics there. ## When to use them - **Batch tools** that read large inputs and write large outputs, use only C++ streams, and run single-threaded or with their own output lock: both calls are reasonable, placed at the top of `main`. - **Interactive tools**: keep the tie, or flush prompts explicitly. - **Code that also uses C stdio**, including libraries that print with `printf`: keep synchronisation on. ## A checklist for a fast batch tool 1. Replace every `std::endl` in loops with `'\n'`. 2. Put `std::ios::sync_with_stdio(false);` and `std::cin.tie(nullptr);` as the first statements of `main`, only if the program and its libraries use no C stdio on the standard streams. 3. Write diagnostics to `std::cerr`, which stays unit-buffered. 4. If several threads print, give `std::cout` one lock or one writer thread. 5. Flush explicitly before anything that waits on a human or another process. ## Measure before and after The speedup depends on the standard library, the destination, and the I/O pattern, so measure the real workload with input redirected from a file. Often the first fix is elsewhere: replacing `std::endl` with `'\n'` removes a flush per line regardless of these settings.
- Why does std::cin.tie(nullptr) speed up a read-and-print loop even when synchronisation is left on?With the tie, each input operation may first flush `std::cout`, so output leaves in tiny pieces between reads. Removing the tie lets `std::cout` fill its buffer and write in large blocks. The trade-off is that prompts no longer appear automatically before input.
- What happens if sync_with_stdio(false) is called after the program has already printed something?The standard makes the effect implementation-defined when any input or output has already occurred on the standard streams. The program may keep synchronised behaviour, switch partway, or lose ordering between earlier and later output, so the call belongs at the start of `main`.
- sync_with_stdio(false) is safe to call at any point in the program
- After sync_with_stdio(false), printf and cout still interleave in order
- cin.tie(nullptr) disables buffering of std::cout
- sync_with_stdio(false) only affects std::cin, not the output streams
- The speedup is the same on every standard library implementation