gpt4 book ai didi

python - 与 C++ 相比,为什么 Python 中的系统调用要慢得多?

转载 作者:行者123 更新时间:2023-11-28 00:24:41 26 4
gpt4 key购买 nike

我有 2 个相同的代码,它们完成相同的任务。一个代码是用 python 编写的,另一个是用 c++ 编写的。所有代码所做的就是调用一个可执行文件(可执行文件生成一个 ascii 文件)。在 C++ 中,我使用 system() 命令来调用可执行文件。在 python 中,我使用了很多东西,包括 os.system subprocess.call subprocess.popen

我意识到 C++ 是编译型语言,而 Python 是解释型语言。而且我也意识到 python 调用有更多的开销。但是 c++ 代码比 python 代码快近 100 倍。 c++ 时间约为 0.004 秒。 python 时间约为 0.35 秒。

即使是一个简单的 pwd 命令,使用 python 所花费的时间也是使用 c++ 的 10 倍以上。如果开销是导致 python 代码变慢的原因,那么 python 中是否有比我已经尝试过的更快的选项?

这是一个简单的python代码:

from os import system
from time import time

t0 = time();
system("pwd");
print "duration: ",time()-t0;

在 C++ 中也是一样:

#include <iostream>
#include <sys/time.h>
double diff(timespec start, timespec end) { return (end.tv_nsec-start.tv_nsec)/1e9; }

int main()
{
timespec t0, t1;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, & t0);
system("pwd");
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, & t1);

std::cout << "duration: " << diff(t0,t1) << "\n";

return 0;
}

我使用 gcc 来编译 C++ 代码。您必须使用 -lrt 选项才能使代码正确编译。

您可以自己运行代码。我的计时方法可能是错误的。但如果它们没问题,那么与 c++ 可执行文件相比,python 脚本执行 pwd 命令的时间是其 10 倍以上

最佳答案

C 'exec' 调用直接执行程序。

虽然 Python 的“系统”调用首先执行 bash,但 bash 会执行相关程序。

关于python - 与 C++ 相比,为什么 Python 中的系统调用要慢得多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25648831/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com