In this article, we delve into the reasons why reading lines from standard input (stdin) in C performs significantly slower than its Python counterpart.
When comparing the following C and Python codes:
C :
getline(cin, input_line);
Python:
for line in sys.stdin:
Surprising results emerged, with Python outperforming C by an order of magnitude. This discrepancy can be attributed to different default settings in C .
By default, the cin stream in C is synchronized with the standard I/O system (stdio), which causes it to avoid input buffering. This means that cin will read input character by character instead of using larger chunks, resulting in numerous expensive system calls.
To address this limitation, you can disable this synchronization by adding the following statement to the beginning of your main function:
std::ios_base::sync_with_stdio(false);
With this modification, cin will be allowed to buffer its input independently, leading to significant performance gains.
Additionally, you can use the fgets function, which provides a more efficient and direct way to read input lines without incurring the overhead of synchronization.
Summary:
The default synchronization settings in C result in more system calls for buffer management, making it slower than Python for reading stdin input. To improve performance, it is recommended to disable this synchronization or use the fgets function.
The above is the detailed content of Why is C `stdin` Reading So Much Slower Than Python's?. For more information, please follow other related articles on the PHP Chinese website!