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

前端 未结 10 2050
野趣味
野趣味 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:06

    I reproduced the original result on my computer using g++ on a Mac.

    Adding the following statements to the C++ version just before the while loop brings it inline with the Python version:

    std::ios_base::sync_with_stdio(false);
    char buffer[1048576];
    std::cin.rdbuf()->pubsetbuf(buffer, sizeof(buffer));
    

    sync_with_stdio improved speed to 2 seconds, and setting a larger buffer brought it down to 1 second.

提交回复
热议问题