【发布时间】:2012-03-11 09:22:02
【问题描述】:
我想比较使用 Python 和 C++ 从标准输入读取字符串输入的行数,并震惊地发现我的 C++ 代码的运行速度比等效的 Python 代码慢一个数量级。由于我的 C++ 生疏了,而且我还不是 Python 专家,请告诉我我做错了什么或误解了什么。
(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 |
【问题讨论】:
-
您是否多次运行测试?可能是磁盘缓存问题。
-
@VaughnCato 是的,在两台不同的机器上也是如此。
-
问题在于与 stdio 的同步 -- 请参阅我的回答。
-
因为似乎没有人提到为什么你会在 C++ 中多出一行:不要针对
cin.eof()进行测试! 将getline调用放入 'if`声明。 -
wc -l速度很快,因为它一次读取多行流(可能是fread(stdin)/memchr('\n')组合)。 Python 结果的数量级相同,例如wc-l.py
标签: python c++ benchmarking iostream getline