Home >Backend Development >C++ >Why is C 's stdin Input Significantly Slower Than Python's, and How Can It Be Improved?

Why is C 's stdin Input Significantly Slower Than Python's, and How Can It Be Improved?

Susan Sarandon
Susan SarandonOriginal
2024-12-18 11:57:16877browse

Why is C  's stdin Input Significantly Slower Than Python's, and How Can It Be Improved?

Why is reading lines from stdin much slower in C than Python?

Reading lines from standard input (stdin) can be significantly slower in C compared to Python due to different default settings in the C input stream.

Default Buffering

By default, the C input stream (cin) is synchronized with the standard input/output (stdio) streams. This synchronization forces cin to avoid any input buffering, resulting in a one-character-at-a-time read.

Python Buffering

In contrast, the stdin stream in Python is buffered by default, which allows it to read larger chunks of input at once. This reduces the number of system calls needed to read the data, leading to improved performance.

Fixing the C Code

To achieve similar performance in C , you can disable the synchronization with stdio by adding the following line at the beginning of your main function:

std::ios_base::sync_with_stdio(false);

This allows cin to buffer its input and significantly improves the read speed.

fgets vs. getline

Additionally, you could consider using fgets instead of getline(), which is a C function that reads a line of text from a file or standard input. fgets has the advantage of not requiring dynamic memory allocation, further improving performance.

Performance Comparison

Below is a table comparing the lines per second (LPS) for different approaches using a 100M line file:

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

As you can see, disabling synchronization or using fgets significantly improves the performance of C .

The above is the detailed content of Why is C 's stdin Input Significantly Slower Than Python's, and How Can It Be Improved?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn