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

前端 未结 10 1801
野趣味
野趣味 2020-11-22 03:06

I wanted to compare reading lines of string input from stdin using Python and C++ and was shocked to see my C++ code run an order of magnitude slower than the equivalent Pyt

10条回答
  •  心在旅途
    2020-11-22 03:45

    A first element of an answer: is slow. Damn slow. I get a huge performance boost with scanf as in the below, but it is still two times slower than Python.

    #include 
    #include 
    #include 
    
    using namespace std;
    
    int main() {
        char buffer[10000];
        long line_count = 0;
        time_t start = time(NULL);
        int sec;
        int lps;
    
        int read = 1;
        while(read > 0) {
            read = scanf("%s", buffer);
            line_count++;
        };
        sec = (int) time(NULL) - start;
        line_count--;
        cerr << "Saw " << line_count << " lines in " << sec << " seconds." ;
        if (sec > 0) {
            lps = line_count / sec;
            cerr << "  Crunch speed: " << lps << endl;
        } 
        else
            cerr << endl;
        return 0;
    }
    

提交回复
热议问题