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

问题描述 投票:1675回答:10

我想比较使用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 << endl;
    } else
        cerr << endl;
    return 0;
}

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

Python等价物:

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

这是我的结果:

$ 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

我应该注意到,我在Mac OS X v10.6.8(Snow Leopard)和Linux 2.6.32(Red Hat Linux 6.2)下都尝试过这一点。前者是MacBook Pro,后者是一个非常强大的服务器,而不是太过贴切。

$ 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
python c++ benchmarking iostream getline
10个回答
1509
投票

默认情况下,cin与stdio同步,这会导致它避免任何输入缓冲。如果将其添加到主页的顶部,您应该会看到更好的性能:

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函数一次读取一个字符。不幸的是,这引入了很多开销。对于少量输入,这不是一个大问题,但是当您阅读数百万行时,性能损失是显着的。

幸运的是,图书馆设计师决定,如果你知道自己在做什么,你也应该能够禁用这个功能来提高性能,所以他们提供了dtruss/strace方法。


10
投票

好吧,我看到你在第二个解决方案中从scanf切换到scanf,这是我要给你的第一个建议(cin是sloooooooooooow)。现在,如果你从fgets切换到fgets,你会看到性能的另一个提升:fgets是字符串输入最快的C ++函数。

BTW,不知道那个同步的东西,不错。但你仍然应该尝试qazxswpoi。


151
投票

出于好奇,我已经看过引擎盖下发生了什么,我在每次测试中都使用了./a.out < in Saw 6512403 lines in 8 seconds. Crunch speed: 814050

C ++

sudo dtruss -c ./a.out < in

系统调用CALL COUNT __mac_syscall 1 <snip> open 6 pread 8 mprotect 17 mmap 22 stat64 30 read_nocancel 25958

./a.py < in
Read 6512402 lines in 1 seconds. LPS: 6512402

蟒蛇

sudo dtruss -c ./a.py < in

系统调用CALL COUNT __mac_syscall 1 <snip> open 5 pread 8 mprotect 17 mmap 21 stat64 29

$ /usr/bin/time cat big_file | program_to_benchmark

126
投票

我在这里落后了几年,但是:

在原始帖子的“编辑4/5/6”中,您正在使用构造:

'Useless Use Of Cat'

这有两种不同的方式:

  1. 你实际上计时执行'cat`,而不是你的基准。 `time`显示的'user'和'sys'CPU使用率是`cat`,而不是你的基准程序。更糟糕的是,“真实”时间也不一定准确。根据本地操作系统中“cat”和管道的实现,“cat”可能会写入最终的巨型缓冲区,并在读取器进程完成其工作之前很久就会退出。
  2. 使用“猫”是不必要的,事实上适得其反;你正在添加移动部件。如果你使用的是一个足够旧的系统(即使用单个CPU并且 - 在某些代码的计算机中 - I / O比CPU快) - “cat”运行这一事实可能会对结果产生很大的影响。你也受到任何输入和输出缓冲以及其他处理`cat`的影响。 (如果我是Randal Schwartz,这可能会让你获得$ /usr/bin/time program_to_benchmark < big_file 奖。

更好的结构是:

$ cat big_file | /usr/bin/time program_to_benchmark

在这个语句中,它是打开big_file的shell,将它传递给你的程序(好吧,实际上是`time`然后执行你的程序作为子进程)作为已打开的文件描述符。 100%的文件读取完全是您尝试进行基准测试的程序的责任。这可以让您真正了解其性能而不会出现虚假的并发症。

我将提到两个可能的,但实际上是错误的,“修复”也可以考虑(但我'他们'他们不同,因为这些不是原始帖子中的错误):

答:您可以通过仅计划您的计划来“修复”此问题:

$ /usr/bin/time sh -c 'cat big_file | program_to_benchmark'

B.或通过计时整个管道:

$ /usr/bin/time cat temp_big_file | wc -l
0.01user 1.34system 0:01.83elapsed 74%CPU ...

出于与#2相同的原因,这些是错误的:他们仍然不必要地使用`cat`。我提到它们有几个原因:

  • 对于那些对POSIX shell的I / O重定向工具不太满意的人来说,它们更“自然”
  • 可能存在需要`cat`的情况(例如:要读取的文件需要某种特权才能访问,并且您不希望将该特权授予要进行基准测试的程序:`sudo cat / dev / sda | / usr / bin / time my_compression_test --no-output`)
  • 实际上,在现代机器上,管道中添加的“猫”可能没有实际意义

但我有点犹豫地说最后一件事。如果我们检查“编辑5”中的最后一个结果 -

$ /usr/bin/time wc -l < temp_big_file

- 这声称`cat`在测试期间消耗了74%的CPU;实际上1.34 / 1.83约为74%。也许是一阵:

$ time wc -l < /tmp/junk
real 0.280s user 0.156s sys 0.124s (total cpu 0.280s)
$ time cat /tmp/junk | wc -l
real 0.407s user 0.157s sys 0.618s (total cpu 0.775s)
$ time sh -c 'cat /tmp/junk | wc -l'
real 0.411s user 0.118s sys 0.660s (total cpu 0.778s)

本来只剩下.49秒!可能不是:`cat`在这里必须支付read()系统调用(或等效),它从'disk'(实际上是缓冲区缓存)传输文件,以及管道写入将它们传递给`wc`。正确的测试仍然必须进行read()调用;只保存了write-to-pipe和read-from-pipe调用,这些调用应该相当便宜。

不过,我预测你可以衡量`cat file |之间的区别wc -l`和`wc -l <​​file`并找到明显的(2位数百分比)差异。每个较慢的测试都会在绝对时间内付出类似的代价;然而,这将占其较长总时间的较小部分。

事实上,我在Linux 3.13(Ubuntu 14.04)系统上使用1.5千兆字节的垃圾文件进行了一些快速测试,获得了这些结果(这些实际上是“最好的3个”结果;当然是在启动缓存之后):

while

请注意,两个管道结果声称占用的CPU时间(用户+ sys)比实时多。这是因为我使用shell(Bash)的内置'time'命令,它认识到了管道;我在多核机器上,管道中的单独进程可以使用单独的内核,比实时更快地累积CPU时间。使用/ usr / bin / time我看到比实时更小的CPU时间 - 表明它只能在命令行上传递给它的单个管道元素。另外,shell的输出给出了毫秒,而/ usr / bin / time只给出了一秒的hundreth。

因此,在`wc -l`的效率级别,`cat`产生了巨大的差异:409/283 = 1.453或45.3%更多实时,775/280 = 2.768,或者使用的CPU高出177%!在我的随机它是在那时的测试框。

我应该补充一点,这些测试方式之间至少还有一个显着的区别,我不能说它是好处还是错误;你必须自己决定:

当你运行`cat big_file | / usr / bin / time my_program`,你的程序正在接收来自管道的输入,正好是'cat`发送的速度,并且不大于`cat`所写的块。

运行`/ usr / bin / time my_program <big_file`时,程序会收到实际文件的打开文件描述符。您的程序 - 或者在许多情况下是编写它的语言的I / O库 - 在呈现引用常规文件的文件描述符时可能会采取不同的操作。它可以使用mmap(2)将输入文件映射到其地址空间,而不是使用显式的read(2)系统调用。这些差异对基准测试结果的影响要大于运行`cat`二进制文件的小成本。

当然,如果同一程序在两种情况下的表现有很大差异,那么这是一个有趣的基准测试结果。它表明,实际上,程序或其I / O库正在做一些有趣的事情,比如使用mmap()。所以在实践中,以两种方式运行基准测试可能会很好;或许用一些小因素来折扣“猫”结果,以“原谅”运行“猫”本身的成本。


86
投票

我在Mac上使用g ++在计算机上复制了原始结果。

Python循环之前将以下语句添加到C ++版本使其与std::ios_base::sync_with_stdio(false); char buffer[1048576]; std::cin.rdbuf()->pubsetbuf(buffer, sizeof(buffer)); 版本内联:

getline

sync_with_stdio将速度提高到2秒,设置更大的缓冲区使其降低到1秒。


37
投票

如果你不关心文件加载时间或加载小文本文件,scanf,流操作符,//open file in binary mode std::fstream file( filename, std::ios::in|::std::ios::binary ); if( !file ) return NULL; //read the size... file.seekg(0, std::ios::end); size_t length = (size_t)file.tellg(); file.seekg(0, std::ios::beg); //read into memory buffer, then close it. char *filebuf = new char[length+1]; file.read(filebuf, length); filebuf[length] = '\0'; //make it null-terminated file.close(); 可以很方便。但是,如果性能是您关心的,那么您应该将整个文件缓冲到内存中(假设它适合)。

这是一个例子:

std::istrstream header(&filebuf[0], length);

如果需要,可以在该缓冲区周围包装一个流,以便更方便地访问:

while (cin) {
    getline(cin, input_line);

    if (!cin.eof())
        line_count++;
};

此外,如果您控制文件,请考虑使用平面二进制数据格式而不是文本。读取和写入更可靠,因为您不必处理空白的所有歧义。解析时它也更小,速度更快。


16
投票

顺便说一句,C ++版本的行数大于Python版本的行数的原因是eof标志仅在尝试读取超出eof时才设置。所以正确的循环是:

const int buffer_size = 500 * 1024;  // Too large/small buffer is not good.
std::vector<char> 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'; });
}

15
投票

以下代码对我来说比目前为止发布的其他代码更快:( Visual Studio 2013,64位,500 MB文件,行长度统一为[0,1000))。

<iostream>

它击败我所有的Python尝试超过2倍。


13
投票

在你的第二个例子中(使用scanf()),为什么这仍然较慢可能是因为scanf(“%s”)解析字符串并查找任何空格char(空格,制表符,换行符)。

此外,是的,CPython做了一些缓存以避免硬盘读取。


11
投票

答案的第一个要素:scanf很慢。该死的慢。我使用#include <iostream> #include <time.h> #include <cstdio> 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; } 获得了巨大的性能提升,如下所示,但它仍然比Python快两倍。

cin
© www.soinside.com 2019 - 2024. All rights reserved.