Why is reading lines from stdin much slower in C than Python?
Problem:
When comparing Python and C code for reading lines of string input from stdin, Python code executes significantly faster. Despite ensuring proper C implementation, the Python equivalent outperforms it by an order of magnitude.
Default Settings and System Calls:
In Python, input buffering is enabled by default, leading to efficient large chunk reads and fewer system calls. In contrast, C streams are synchronized with stdio, compelling cin to skip input buffering and read characters individually. This choice, intended to prevent conflicts with stdio functions, inadvertently introduces significant overhead.
Performance Optimization:
To improve C performance, include the statement cin.sync_with_stdio(false) at the beginning of main. This disables stream synchronization and permits independent buffering, substantially enhancing input read speed.
Alternative Options:
Another high-performance alternative to cin is fgets, which employs stdio functions for direct input reading.
Comparison Results:
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 (not fair comparison) | 54,644,808 |
The above is the detailed content of Why is C 's `cin` Significantly Slower Than Python's `input()` for Reading Lines from Standard Input, and How Can Performance Be Improved?. For more information, please follow other related articles on the PHP Chinese website!