繁体   English   中英

为什么与C ++相比,Python中的系统调用这么慢?

[英]why are system calls so much slower in python compared to c++?

在完成相同任务的意义上,我有2个相同的代码。 一种代码是用python编写的,另一种则是用c ++编写的。 所有代码要做的就是调用一个可执行文件(该可执行文件生成一个ascii文件)。 在C ++中,我使用system()命令调用可执行文件。 在蟒蛇,我已经使用了许多事情,包括os.system subprocess.call subprocess.popen

我意识到在解释python的同时,c ++是一种编译语言。 而且我还意识到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 ++可执行文件相比,执行pwd命令所需的python脚本时间要长10倍以上

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

当Python的“系统”调用首先执行bash时,它将执行相关程序。

您可以直接在python中使用execvp

import os

binary = "ls"
options = [binary, "-l"]

newpid = os.fork()
if newpid == 0:
     # we are in the child process
     os.execvp(binary, options)
     os._exit(1)

os.wait()
print "executed", " ".join(options)

我编写了一个小脚本,执行时间比您看到的要快得多。

td@timsworld2:~/tmp/so$ cat nothing.py
#!/usr/bin/env python
import subprocess
import sys

cmd = ['python', '-V'] if 'py' in sys.argv else ['pwd']
if 'shell' in sys.argv:
    subprocess.call(' '.join(cmd), shell=True)
else:
    subprocess.call(cmd)


td@timsworld2:~/tmp/so$ time ./nothing.py
/home/td/tmp/so

real    0m0.024s
user    0m0.012s
sys     0m0.008s
td@timsworld2:~/tmp/so$ time python nothing.py
/home/td/tmp/so

real    0m0.020s
user    0m0.012s
sys     0m0.004s
td@timsworld2:~/tmp/so$ time ./nothing.py py
Python 2.7.3

real    0m0.022s
user    0m0.016s
sys     0m0.000s
td@timsworld2:~/tmp/so$ time ./nothing.py sh
/home/td/tmp/so

real    0m0.020s
user    0m0.012s
sys     0m0.004s
td@timsworld2:~/tmp/so$ 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM