专业编程基础技术教程

网站首页 > 基础教程 正文

每日趣问1:同样的代码,Python居然比C++快10倍?

ccvgpt 2024-10-19 03:25:03 基础教程 8 ℃

今天在编写一个从命令行读取数据,并计算一共有多少行的程序时,惊奇地发现C++居然

比如Python慢差不多10倍。这!!!!!

每日趣问1:同样的代码,Python居然比C++快10倍?

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;

}

Python代码:

#!/usr/bin/env python

import time

import sys

count = 0

start_time = 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))


下面测试结果:


从结果来看,Python的性能比C++快了9倍。一下子打破了我对C++一直崇拜的心情。。。

不过快或者慢肯定有它的道理所在,我们就来研究一下Python为什么会比C++快这么多呢??

首先我们使用dtruss命令查看一下C++程序的执行过程:

而Python呢:

可以看出,Python的系统调用比C++少了很多。。。


为什么会这样呢?

首先,在默认的情况下,cin是跟stdio进行“同步(sync)”的。为了实现该目的,cin就只能一个字符一个字符地读取数据,

而没有使用任何的输入缓存区。而如果使用缓冲区时,可以以更大的数据块读取数据,大大减少系统调用。

由于基于FILE*的stdio和iostream是分开实现的,它们都有独立的缓冲区。因此如果将两者一起使用,可能会有问题。

比如下面的代码:

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

如果cin读取的输入比实际需要的输入多时,第二个数值将不会传递给scanf,因为cin有独立的缓冲区。这将导致意外的结果。

幸运的是,标准库的设计者已经考虑到这个问题,你可以将下面的代码加到main函数下面以提升性能:

std::ios_base::sync_with_stdio(false);

这样,C++的性能将大大提升。。。。

Tags:

最近发表
标签列表