为什么等效的Python代码这么慢
有人能解释一下为什么下面这段简单的代码(用欧几里得算法找最大公约数的实现)比Ruby中的相应代码慢大约三倍吗?
iter_gcd.py的内容:
from sys import argv,stderr
def gcd(m, n):
if n > m:
m, n = n, m
while n != 0:
rem = m % n
m = n
n = rem
return m
# in Python3 code there is xrange replaced with range function
def main(a1, a2):
comp = 0
for j in xrange(a1, 1, -1):
for i in xrange(1, a2):
comp += gcd(i,j)
print(comp)
if __name__ == '__main__':
if len(argv) != 3:
stderr.write('usage: {0:s} num1 num2\n'.format(argv[0]))
exit(1)
else:
main(int(argv[1]), int(argv[2]))
iter_gcd.rb的内容:
def gcd(m, n)
while n != 0
rem = m % n
m = n
n = rem
end
return m
end
def main(a1, a2)
comp = 0
a1.downto 2 do
|j|
1.upto (a2 - 1) do
|i|
comp += gcd(i,j)
end
end
puts comp
end
if __FILE__ == $0
if ARGV.length != 2
$stderr.puts('usage: %s num1 num2' % $0)
exit(1)
else
main(ARGV[0].to_i, ARGV[1].to_i)
end
end
执行时间测量:
$ time python iter_gcd.py 4000 3000
61356305
real 0m22.890s
user 0m22.867s
sys 0m0.006s
$ python -V
Python 2.6.4
$ time python3 iter_gcd.py 4000 3000
61356305
real 0m18.634s
user 0m18.615s
sys 0m0.009s
$ python3 -V
Python 3.1.2
$ time ruby iter_gcd.rb 4000 3000
61356305
real 0m7.619s
user 0m7.616s
sys 0m0.003s
$ ruby -v
ruby 1.9.2p0 (2010-08-18 revision 29036) [x86_64-linux]
我只是好奇为什么会得到这样的结果。我原本认为CPython在大多数情况下比MRI快,甚至比新的Ruby 1.9在YARV上还快,但这个“小基准测试”真的让我很惊讶。
顺便说一下,我知道可以使用像fractions.gcd这样的专用库函数,但我想比较一下这些基本和简单的语言构造的实现。
我是不是漏掉了什么,还是下一代Ruby的实现速度提升得这么明显?
4 个回答
我记得Ruby处理整数的方式和Python不太一样,所以我猜测Python可能花了很多时间在分配内存上,而Ruby则是直接在原地修改整数。
顺便提一下,使用Pypy 1.4可以把我系统上Python版本的运行时间从大约15秒减少到不到3秒。
我可以确认,在我的电脑上,ruby1.9在这个“小测试”中比CPython要快:
| Interpreter | Time, s | Ratio |
|---------------------------------+---------+-------|
| python-2.6 (cython_gcd.gcd_int) | 2.8 | 0.33 |
| pypy-1.4 | 3.5 | 0.41 |
| jython-2.5 (java "1.6.0_20") | 4.7 | 0.55 |
| python-2.6 (cython_gcd.gcd) | 5.6 | 0.65 |
| ruby-1.9 | 8.6 | 1.00 |
| jython-2.5 | 8.9 | 1.03 |
| python-3.2 | 11.0 | 1.28 |
| python-2.6 | 15.9 | 1.85 |
| ruby-1.8 | 42.6 | 4.95 |
#+TBLFM: $3=$2/@6$2;%.2f
通过性能分析工具(python -mcProfile iter_gcd.py 4000 3000
),可以看到80%的时间都花在调用gcd()
函数上,所以确实是gcd()
函数的表现影响了结果。
我用Cython为Python写了一个cython_gcd
的扩展,文件名是cython_gcd.pyx
:
def gcd(m, n):
while n:
n, m = m % n, n
return m
def gcd_int(int m, int n):
while n:
n, m = m % n, n
return m
在iter_gcd.py
中使用这个扩展的方法是:from cython_gcd import gcd, gcd_int
。
如果想试试这个扩展,可以运行:python setup.py build_ext --inplace
,其中setup.py
:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [Extension("cython_gcd", ["cython_gcd.pyx"])]
setup(
name = 'Hello world app',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)
如果想全局安装这个扩展,可以运行python setup.py install
。
总结
“因为在Python中调用函数的开销比在Ruby中大得多。”
详细信息
这个测试只是个小基准,实际上并不能全面反映这两种语言在实际使用中的性能。通常你会想要重写程序,以便更好地利用Python和Ruby各自的优势,但这确实展示了Python目前的一个弱点。速度差异的根本原因在于函数调用的开销。我做了一些测试来说明这一点。下面有代码和更多细节。在Python的测试中,我使用了2000作为gcd的两个参数。
Interpreter: Python 2.6.6
Program type: gcd using function call
Total CPU time: 29.336 seconds
Interpreter: Python 2.6.6
Program type: gcd using inline code
Total CPU time: 13.194 seconds
Interpreter: Python 2.6.6
Program type: gcd using inline code, with dummy function call
Total CPU time: 30.672 seconds
这告诉我们,造成时间差异的主要原因并不是gcd函数的计算,而是函数调用本身。在Python 3.1中,差异也是类似的:
Interpreter: Python 3.1.3rc1
Program type: gcd using function call
Total CPU time: 30.920 seconds
Interpreter: Python 3.1.3rc1
Program type: gcd using inline code
Total CPU time: 15.185 seconds
Interpreter: Python 3.1.3rc1
Program type: gcd using inline code, with dummy function call
Total CPU time: 33.739 seconds
同样,实际的计算并不是最大的影响因素,影响最大的还是函数调用本身。在Ruby中,函数调用的开销要小得多。(注意:我在Ruby版本的程序中使用了较小的参数(200),因为Ruby的性能分析工具会显著降低实时性能。不过这并不影响CPU时间的性能。)
Interpreter: ruby 1.9.2p0 (2010-08-18 revision 29036) [i486-linux]
Program type: gcd using function call
Total CPU time: 21.66 seconds
Interpreter: ruby 1.9.2p0 (2010-08-18 revision 29036) [i486-linux]
Program type: gcd using inline code
Total CPU time: 21.31 seconds
Interpreter: ruby 1.8.7 (2010-08-16 patchlevel 302) [i486-linux]
Program type: gcd using function call
Total CPU time: 27.00 seconds
Interpreter: ruby 1.8.7 (2010-08-16 patchlevel 302) [i486-linux]
Program type: gcd using inline code
Total CPU time: 24.83 seconds
注意,无论是Ruby 1.8还是1.9,gcd函数的调用都没有受到太大影响——函数调用和内联版本的性能差不多。Ruby 1.9似乎表现得更好,函数调用和内联版本之间的差异更小。
所以问题的答案是:“因为在Python中调用函数的开销比在Ruby中大得多。”
代码
# iter_gcd -- Python 2.x version, with gcd function call
# Python 3.x version uses range instead of xrange
from sys import argv,stderr
def gcd(m, n):
if n > m:
m, n = n, m
while n != 0:
rem = m % n
m = n
n = rem
return m
def main(a1, a2):
comp = 0
for j in xrange(a1, 1, -1):
for i in xrange(1, a2):
comp += gcd(i,j)
print(comp)
if __name__ == '__main__':
if len(argv) != 3:
stderr.write('usage: {0:s} num1 num2\n'.format(argv[0]))
exit(1)
else:
main(int(argv[1]), int(argv[2]))
# iter_gcd -- Python 2.x version, inline calculation
# Python 3.x version uses range instead of xrange
from sys import argv,stderr
def main(a1, a2):
comp = 0
for j in xrange(a1, 1, -1):
for i in xrange(1, a2):
if i < j:
m, n = j, i
else:
m, n = i, j
while n != 0:
rem = m % n
m = n
n = rem
comp += m
print(comp)
if __name__ == '__main__':
if len(argv) != 3:
stderr.write('usage: {0:s} num1 num2\n'.format(argv[0]))
exit(1)
else:
main(int(argv[1]), int(argv[2]))
# iter_gcd -- Python 2.x version, inline calculation, dummy function call
# Python 3.x version uses range instead of xrange
from sys import argv,stderr
def dummyfunc(n, m):
a = n + m
def main(a1, a2):
comp = 0
for j in xrange(a1, 1, -1):
for i in xrange(1, a2):
if i < j:
m, n = j, i
else:
m, n = i, j
while n != 0:
rem = m % n
m = n
n = rem
comp += m
dummyfunc(i, j)
print(comp)
if __name__ == '__main__':
if len(argv) != 3:
stderr.write('usage: {0:s} num1 num2\n'.format(argv[0]))
exit(1)
else:
main(int(argv[1]), int(argv[2]))
# iter_gcd -- Ruby version, with gcd function call
def gcd(m, n)
if n > m
m, n = n, m
end
while n != 0
rem = m % n
m = n
n = rem
end
return m
end
def main(a1, a2)
comp = 0
a1.downto 2 do
|j|
1.upto a2-1 do
|i|
comp += gcd(i,j)
end
end
puts comp
end
if __FILE__ == $0
if ARGV.length != 2
$stderr.puts('usage: %s num1 num2' % $0)
exit(1)
else
main(ARGV[0].to_i, ARGV[1].to_i)
end
end
# iter_gcd -- Ruby version, with inline gcd
def main(a1, a2)
comp = 0
a1.downto 2 do |j|
1.upto a2-1 do |i|
m, n = i, j
if n > m
m, n = n, m
end
while n != 0
rem = m % n
m = n
n = rem
end
comp += m
end
end
puts comp
end
if __FILE__ == $0
if ARGV.length != 2
$stderr.puts('usage: %s num1 num2' % $0)
exit(1)
else
main(ARGV[0].to_i, ARGV[1].to_i)
end
end
测试运行
最后,用于运行Python和Ruby并进行性能分析的命令是 pythonX.X -m cProfile iter_gcdX.py 2000 2000
用于Python,和 rubyX.X -rprofile iter_gcdX.rb 200 200
用于Ruby。之所以会有差异,是因为Ruby的性能分析工具增加了很多开销。结果依然有效,因为我比较的是函数调用和内联代码之间的差异,而不是Python和Ruby之间的差异。