为什么Python的系统调用比C++慢这么多?
我有两个代码片段,它们的功能是一样的,都是用来完成同样的任务。一个是用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
选项才能正确编译代码。
你可以自己运行这些代码。我的计时方法可能有误。但如果是正确的,那么Python脚本执行pwd
命令的时间比C++可执行文件要长超过10倍。
3 个回答
1
我写了一个小脚本,运行的速度比你看到的要快很多。
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$
1
你可以直接在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)
1
C语言中的'exec'调用是直接执行程序的。
而Python中的'system'调用则是先执行bash,然后再由bash去执行你想要的程序。