问题描述
见 这个 python 代码有什么问题吗,为什么它比 ruby 运行得这么慢? 用于我之前尝试理解 python 和 ruby 之间的差异.
See Is there something wrong with this python code, why does it run so slow compared to ruby? for my previous attempt at understanding the differences between python and ruby.
正如 igouy 所指出的,我想出的 Python 变慢的原因可能不是由于递归函数调用(涉及堆栈).
As pointed out by igouy the reasoning I came up with for python being slower could be something else than due to recursive function calls (stack involved).
这是我做的
#!/usr/bin/python2.7
i = 0
a = 0
while i < 6553500:
i += 1
if i != 6553500:
a = i
else:
print "o"
print a
在红宝石中是
#!/usr/bin/ruby
i = 0
a = 0
while i < 6553500
i += 1
if i != 6553500
a = i
else
print "o"
end
end
print a
Python 3.1.2(r312:79147,2010 年 10 月 4 日,12:45:09)[GCC 4.5.1] 在 linux2 上
Python 3.1.2 (r312:79147, Oct 4 2010, 12:45:09)[GCC 4.5.1] on linux2
时间python pytest.pyo
time python pytest.pyo
6553499
真正的 0m3.637s
real 0m3.637s
用户 0m3.586s
user 0m3.586s
ruby 1.9.2p0 (2010-08-18 修订版 29036) [x86_64-linux]时间 ruby rutest.rb
ruby 1.9.2p0 (2010-08-18 revision 29036) [x86_64-linux]time ruby rutest.rb
o6553499
真正的 0m0.618s
real 0m0.618s
用户 0m0.610s
user 0m0.610s
让它循环得更高会产生更大的差异.添加一个额外的0,ruby在7s内完成,而python运行了40s.
Letting it loop higher gives higher differences. Adding an extra 0, ruby finishes in 7s, while python runs for 40s.
这是在 Intel(R) Core(TM) i7 CPU M 620 @ 2.67GHz 和 4GB 内存上运行的.
This is run on Intel(R) Core(TM) i7 CPU M 620 @ 2.67GHz with 4GB mem.
为什么会这样?
推荐答案
首先,请注意您显示的 Python 版本不正确:您在 Python 2.7 中运行此代码,而不是 3.1(它甚至不是有效的 Python3 代码).(仅供参考,Python 3 通常比 2 慢.)
First off, note that the Python version you show is incorrect: you're running this code in Python 2.7, not 3.1 (it's not even valid Python3 code). (FYI, Python 3 is usually slower than 2.)
也就是说,Python 测试中存在一个关键问题:您将其编写为全局代码.你需要把它写成一个函数.在正确编写时,它的运行速度大约是 Python 2 和 3 的两倍:
That said, there's a critical problem in the Python test: you're writing it as global code. You need to write it as a function. It runs about twice as fast when written correctly, in both Python 2 and 3:
def main():
i = 0
a = 0
while i < 6553500:
i += 1
if i != 6553500:
a = i
else:
print("o")
print(a)
if __name__ == "__main__":
main()
当你全局编写代码时,你没有本地人;您的所有变量都是全局变量.在 Python 中,局部变量比全局变量快得多,因为全局变量存储在 dict
中.本地可以通过索引直接被 VM 引用,因此不需要查找哈希表.
When you write code globally, you have no locals; all of your variables are global variables. Locals are much faster than globals in Python, because globals are stored in a dict
. Locals can be referenced directly by the VM by index, so no hash table lookups are needed.
另外,请注意,这是一个如此简单的测试,您真正要做的是对一些任意字节码操作进行基准测试.
Also, note that this is such a simple test, what you're really doing is benchmarking a few arbitrary bytecode operations.
这篇关于为什么即使使用这个非常简单的“测试",python 也比 Ruby 慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!