Home > Article > Backend Development > Is `scanf()` Really Faster Than `cin` in C , and How Can We Optimize `cin`\'s Performance?
Is Using scanf() in C Programs Faster than cin?
The claim that using scanf() is faster than cin when reading input in C has some truth to it. Here's an explanation:
Speed Benchmarking
To verify the claim, a simple test program was created to read a list of numbers from standard input and calculate their exclusive OR (XOR) operation. Two versions of the program were tested: one using iostream (cin and cout) and the other using stdio (scanf and printf).
When tested with a large amount of input (33,280,276 random numbers), the scanf version significantly outperformed the iostream version, completing the task in 6.4 seconds compared to 24.3 seconds.
Reason for Speed Difference
The speed difference arises due to iostream's synchronization with C's I/O functions. Input and output operations using iostream are synchronized with the C I/O functions (e.g., getchar(), putchar()), which introduces additional overhead.
Optimization with ios::sync_with_stdio(false)
To address this synchronization issue, std::ios::sync_with_stdio(false) can be used to disable the synchronization between iostream and stdio. This allows iostream to operate more efficiently without the overhead of synchronization.
After disabling synchronization, the performance of the iostream version improved significantly, completing the task in 5.5 seconds, faster than the scanf version.
Conclusion
Based on the benchmarking results, using scanf() is indeed faster than using cin when reading a large amount of input in C programs. However, with the optimization of std::ios::sync_with_stdio(false), iostream can potentially outperform scanf() and should be considered the preferred choice for input and output operations.
The above is the detailed content of Is `scanf()` Really Faster Than `cin` in C , and How Can We Optimize `cin`\'s Performance?. For more information, please follow other related articles on the PHP Chinese website!