Why is C++ slower to read than Python?

Asked 1 years ago, Updated 1 years ago, 108 views

I ran a program that receives a line from stdin in Python and c++ C++ is much slower.

Isn't Python usually much slower?

Is it because I made the code weird? I don't know what's wrong

I ran it on OS X (10.6.8) and Linux (RHEL 6.2)

C++ code:

#include <iostream>
#include <time.h>

using namespace std;

int main() {
    string input_line;
    long line_count = 0;
    time_t start = time(NULL);
    int sec;
    int lps;                                                                   

    while (cin) {
        getline(cin, input_line);
        if (!cin.eof())
            line_count++;
    };

    sec = (int) time(NULL) - start;
    cerr << "Read " << line_count << " lines in " << sec << " seconds." ;
    if (sec > 0) {
        lps = line_count / sec;
        cerr << " LPS: " << lps << endl;
    } } else
        cerr << endl;
    return 0;
}
Compile with //g++ -O3-o readline_test_cppfoo.cpp
#!/usr/bin/env python
import time
import sys

count = 0
start = time.time()

for line in  sys.stdin:
    count += 1

delta_sec = int(time.time() - start_time)
if delta_sec >= 0:
    lines_per_sec = int(round(count/delta_sec))
    print("Read {0} lines in {1} seconds. LPS: {2}".format(count, delta_sec,
       lines_per_sec))

Result:

$ cat test_lines | ./readline_test_cpp 
Read 5570000 lines in 9 seconds. LPS: 618889

$cat test_lines | ./readline_test.py 
Read 5570000 lines in 1 seconds. LPS: 5570000

c++ python readline getline benchmark

2022-09-21 17:25

1 Answers

cin is synchronized with stdio. I don't wait for the input buffer to be full, I just bring it back whenever there's something in the buffer.

std::ios_base::sync_with_stdio(false);

If you add , synchronization will be turned off, which will speed up.

buffered input stream reads data of enormous size (relatively) at once. This reduces the number of system call times when reading one by one (cin corresponds to this) It's much faster.

However, this method should be used carefully in FILE*. Regarding FILE*, stdio and iostream have different implementation methods Therefore, it is not recommended to share the two because they use different buffers.

For example, cin and scanf() write different buffers in the following code If scin has read more than you think, scanf() may not be able to read the second integer. This can lead to unexpected situations.

int myvalue1;
cin >> myvalue1;
int myvalue2;
scanf("%d",&myvalue2);

To avoid this situation, stdio is synchronized with stream as the default value. However, as the input size increases, the speed difference between the synchronized/non-synchronized code becomes too large std::ios_base::sync_with_stdio(false); It allows the programmer to choose whether to synchronize or not, as shown in .


2022-09-21 17:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.