相关疑难解决方法(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万
查看次数

c ++ stringstream太慢了,怎么加快?

可能重复:
在C++中从文本文件中读取数值的最快方法(在这种情况下为double)

#include <ctime>
#include <cstdlib>
#include <string>
#include <sstream>
#include <iostream>
#include <limits>

using namespace std;

static const double NAN_D = numeric_limits<double>::quiet_NaN();

void die(const char *msg, const char *info)
{
    cerr << "** error: " << msg << " \"" << info << '\"';
    exit(1);
}

double str2dou1(const string &str)
{
    if (str.empty() || str[0]=='?') return NAN_D;
    const char *c_str = str.c_str();
    char *err;
    double x = strtod(c_str, &err);
    if (*err != 0) die("unrecognized numeric data", c_str);
    return x; …
Run Code Online (Sandbox Code Playgroud)

c++ performance parsing

18
推荐指数
4
解决办法
2万
查看次数

标签 统计

c++ ×2

benchmarking ×1

getline ×1

iostream ×1

parsing ×1

performance ×1

python ×1