Appearance
Why is reading lines from stdin much slower in C++ than Python?
Reading from stdin can appear slower in C++ than in Python for a few reasons:
- Default synchronization overhead: By default, C++
iostreams (std::cin) are synchronized with Cstdio(stdin). This synchronization adds overhead and prevents certain optimizations, making it slower than Python's default buffered I/O path. - Locale and tie management: C++ streams perform locale-dependent formatting and automatically tie
std::cintostd::cout. This tie forces a flush ofstd::coutbefore every read, which can significantly slow down tight input loops. - Python's I/O is also buffered: Python's
sys.stdinuses block buffering by default. The perceived speed difference usually stems from C++'s default configuration rather than Python's interpreter optimizations.
To make reading from stdin faster in C++, you can disable synchronization and untie the streams. This is the standard approach for high-throughput I/O:
cpp
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);These settings tell the C++ standard library to use its own buffering independently of C stdio and remove the automatic flush before reads. Note that after disabling synchronization, you should not mix std::cin with C functions like scanf or getchar, as their buffers will no longer be aligned.