Why Reading Lines from stdin is Much Slower in C than Python
While comparing input reading speeds in Python and C , it was observed that the C code performed an order of magnitude slower.
cin's Lack of Buffering
This discrepancy arises from a fundamental difference in default behavior. cin in C , by default, is synchronized with standard input/output (stdio), causing it to forego input buffering, resulting in the reading of characters one at a time, an expensive process in terms of system calls.
Solution: Disable Synchronization
To improve performance, cin's synchronization with stdio can be disabled by adding the following line at the beginning of the program:
std::ios_base::sync_with_stdio(false);
This allows C streams to buffer I/O independently, significantly enhancing reading speed.
Straw poll to illustrate the difference:
Implementation | Lines per second |
---|---|
Python (default) | 3,571,428 |
cin (default/naive) | 819,672 |
cin (no sync) | 12,500,000 |
fgets | 14,285,714 |
wc (unfair comparison) | 54,644,808 |
This table demonstrates the vast difference in reading speed when cin's synchronization is disabled.
The above is the detailed content of Why is C 's `cin` Significantly Slower than Python's Input, and How Can It Be Improved?. For more information, please follow other related articles on the PHP Chinese website!