Why is reading lines from stdin much slower in C++ than Python?

The standard input device, or stdin, is used to get input from the system.

stdin in C++

We can read lines from stdin in many ways:

  • Using std::getline:
std::getline(std::cin, line);
  • Using std::cin:
std::cin >> i;

stdin in Python

Reading lines in Python using stdin is done by:

  • input():
inp = input("Type anything")
  • sys.stdin:
import sys
for line in sys.stdin:
print(line)

Enter the input below

Comparison

Utilizing stdin in C++ has numerous ways, yet the default setting in C++ requires more system calls. As a matter of course, cin is synchronized with stdio, keeping it away from any input buffering. It creates additional strides for the library in the C++ stream to blend well with C-style stdio activities. After adding this to the top of our main, we ought to see a vastly improved execution:

std::ios_base::sync_with_stdio(false);

We have to lessen the number of system calls, which are generally costly. For that purpose, the stream will be perused in larger pieces rather than perusing each character one at a time.

The std::cin function flushes the buffer consistently, so it’s anything but a fair examination. Utilizing the C identical ought to be a lot quicker.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved