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

前端 未结 10 1802
野趣味
野趣味 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 04:01

    The following code was faster for me than the other code posted here so far: (Visual Studio 2013, 64-bit, 500 MB file with line length uniformly in [0, 1000)).

    const int buffer_size = 500 * 1024;  // Too large/small buffer is not good.
    std::vector buffer(buffer_size);
    int size;
    while ((size = fread(buffer.data(), sizeof(char), buffer_size, stdin)) > 0) {
        line_count += count_if(buffer.begin(), buffer.begin() + size, [](char ch) { return ch == '\n'; });
    }
    

    It beats all my Python attempts by more than a factor 2.

提交回复
热议问题