相关疑难解决方法(0)

为什么在C++中读取stdin的行比Python要慢得多?

我想比较使用Python和C++从stdin读取字符串的读取行,并且看到我的C++代码运行速度比等效的Python代码慢一个数量级,这让我很震惊.由于我的C++生锈了,我还不是专家Pythonista,请告诉我,如果我做错了什么或者我是否误解了什么.


(TLDR回答:包括声明:cin.sync_with_stdio(false)或者只是fgets改用.

TLDR结果:一直向下滚动到我的问题的底部并查看表格.)


C++代码:

#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 …
Run Code Online (Sandbox Code Playgroud)

c++ python benchmarking iostream getline

1738
推荐指数
10
解决办法
25万
查看次数

标签 统计

benchmarking ×1

c++ ×1

getline ×1

iostream ×1

python ×1