Why Reading Lines from stdin in C Is Slower Than in Python
Despite expectations, C code for reading lines of input from standard input can perform significantly slower than Python counterparts. This discrepancy stems from default settings in C .
Default Input Stream Configuration
By default, the C input stream (cin) is synchronized with standard input/output (stdio). This synchronization means cin attempts to avoid any input buffering, resulting in it reading characters one at a time.
Why Buffering Matters
Typically, input streams buffer input in larger chunks, reducing the number of system calls required for data retrieval. However, separate implementations and buffers for FILE* based stdio and iostreams can lead to problems when used together.
To prevent potential conflicts, streams are synchronized with stdio by default. Cin reads characters one by one, introducing significant overhead, especially when processing millions of lines.
Solution
To improve performance, disable stream synchronization using the sync_with_stdio(false) method at the start of the main function:
std::ios_base::sync_with_stdio(false);
With this change, C streams can buffer independently, resulting in faster input handling.
Alternative Approach: fgets
Another way to improve input speed is to use the fgets function instead of getline:
char buffer[1024]; while (fgets(buffer, sizeof(buffer), stdin)) { // Process the line }
The above is the detailed content of Why is C Standard Input Reading Slower Than Python\'s, and How Can It Be Improved?. For more information, please follow other related articles on the PHP Chinese website!