我想用Python和C++来比较STDIN中的字符串输入的读取行,并震惊地看到我的C++代码运行速度比等效的Python代码慢了一个数量级.因为我的C++生疏了,我还不是一个专家,请告诉我,如果我做错了什么,或者我误解了什么.


(TLDR answer:)包含以下语句:cin.sync_with_stdio(false)或仅使用fgets.

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


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;
}

// Compiled with:
// g++ -O3 -o readline_test_cpp foo.cpp

Python Equivalent:

#!/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))

Here are my results:

$ 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

I should note that I tried this both under Mac OS X v10.6.8 (Snow Leopard) and Linux 2.6.32 (Red Hat Linux 6.2). The former is a MacBook Pro, and the latter is a very beefy server, not that this is too pertinent.

$ for i in {1..5}; do echo "Test run $i at `date`"; echo -n "CPP:"; cat test_lines | ./readline_test_cpp ; echo -n "Python:"; cat test_lines | ./readline_test.py ; done
Test run 1 at Mon Feb 20 21:29:28 EST 2012
CPP:   Read 5570001 lines in 9 seconds. LPS: 618889
Python:Read 5570000 lines in 1 seconds. LPS: 5570000
Test run 2 at Mon Feb 20 21:29:39 EST 2012
CPP:   Read 5570001 lines in 9 seconds. LPS: 618889
Python:Read 5570000 lines in 1 seconds. LPS: 5570000
Test run 3 at Mon Feb 20 21:29:50 EST 2012
CPP:   Read 5570001 lines in 9 seconds. LPS: 618889
Python:Read 5570000 lines in 1 seconds. LPS: 5570000
Test run 4 at Mon Feb 20 21:30:01 EST 2012
CPP:   Read 5570001 lines in 9 seconds. LPS: 618889
Python:Read 5570000 lines in 1 seconds. LPS: 5570000
Test run 5 at Mon Feb 20 21:30:11 EST 2012
CPP:   Read 5570001 lines in 10 seconds. LPS: 557000
Python:Read 5570000 lines in  1 seconds. LPS: 5570000

微小的基准附录和重述

为了完整性,我想我会用同一个文件更新原来的(同步)C++代码的读取速度.同样,这是一个快速磁盘上的100M行文件.以下是几种解决方案/方法的比较:

Implementation Lines per second
python (default) 3,571,428
cin (default/naive) 819,672
cin (no sync) 12,500,000
fgets 14,285,714
wc (not fair comparison) 54,644,808

推荐答案

TL;DR:因为C++中的默认设置不同,需要更多的系统调用.

默认情况下,cin与stdio同步,这使得它可以避免任何输入缓冲.如果将此代码添加到Main的顶部,您应该会看到更好的性能:

std::ios_base::sync_with_stdio(false);

通常,在缓冲输入流时,不是一次读取一个字符,而是以更大的块读取流.这减少了系统调用的数量,而系统调用的成本通常相对较高.然而,由于基于FILE*stdioiostreams通常具有不同的实现,因此具有不同的缓冲器,如果两者一起使用,可能会导致问题.例如:

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

如果cin读取的输入比实际需要的多,那么第二个整数值将不适用于scanf函数,它有自己的独立缓冲区.这将导致意想不到的结果.

为了避免这种情况,默认情况下,流与stdio同步.实现这一点的一种常见方式是让cin使用stdio个函数根据需要一次一个地读取每个字符.不幸的是,这会带来大量开销.对于少量的输入,这不是一个大问题,但是当您读取数百万行时,性能损失是显著的.

幸运的是,库设计人员决定,如果您知道自己在做什么,您也应该能够禁用此功能以获得更好的性能,因此他们提供了sync_with_stdio方法.通过此链接(添加强调):

如果同步关闭,则允许C++标准流独立地缓冲它们的I/O,which may be considerably faster in some cases.

Python相关问答推荐

通过Selenium从页面获取所有H2元素

将两只Pandas rame乘以指数

如何找到满足各组口罩条件的第一行?

将图像拖到另一个图像

C#使用程序从Python中执行Exec文件

DataFrames与NaN的条件乘法

海上重叠直方图

在含噪声的3D点网格中识别4连通点模式

在pandas中使用group_by,但有条件

isinstance()在使用dill.dump和dill.load后,对列表中包含的对象失败

在Python中调用变量(特别是Tkinter)

如何在PySide/Qt QColumbnView中删除列

如果包含特定值,则筛选Groupby

jsonschema日期格式

为什么在Python中00是一个有效的整数?

Pythonquests.get(Url)返回Colab中的空内容

使用xlsxWriter在EXCEL中为数据帧的各行上色

ValueError:必须在Pandas 中生成聚合值

将参数从另一个python脚本中传递给main(argv

极地数据帧:ROLING_SUM向前看