我想比较使用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)