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.
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).
I made this
#!/usr/bin/python2.7
i = 0
a = 0
while i < 6553500:
i += 1
if i != 6553500:
a = i
else:
print "o"
print a
In ruby it is
#!/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, Oct 4 2010, 12:45:09)
[GCC 4.5.1] on linux2
time python pytest.py
o
6553499
real 0m3.637s
user 0m3.586s
ruby 1.9.2p0 (2010-08-18 revision 29036) [x86_64-linux]
time ruby rutest.rb
o6553499
real 0m0.618s
user 0m0.610s
Letting it loop higher gives higher differences. Adding an extra 0, ruby finishes in 7s, while python runs for 40s.
This is run on Intel(R) Core(TM) i7 CPU M 620 @ 2.67GHz with 4GB mem.
Why is this so?
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.)
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:
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.