Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something wrong with this python code, why does it run so slow compared to ruby?

I was interested in comparing ruby speed vs python so I took the simplest recursive calculation, namely print the fibonacci sequance.

This is the python code

#!/usr/bin/python2.7                       
def fib(n):
    if n == 0: 
        return 0
    elif n == 1:
        return 1 
    else:
        return fib(n-1)+fib(n-2)

i = 0
while i < 35:
    print fib(i)
    i = i + 1

and here is the ruby code

#!/usr/bin/ruby

def fib(n)
    if n == 0
        return 0
    elsif n == 1
        return 1
    else
        fib(n-1)+fib(n-2)
    end
end 

i = 0 
while (i < 35)
    puts fib(i)
    i = i + 1 
end

over several runs, time reports this average

real    0m4.782s 
user    0m4.763s 
sys     0m0.010s

thats for ruby, now python2.7 gives

real    0m11.605s
user    0m11.563s
sys     0m0.013s

Whats the deal?

like image 472
rapadura Avatar asked Oct 28 '10 19:10

rapadura


People also ask

Why is my Python code so slow?

Internally Python code is interpreted during run time rather than being compiled to native code hence it is a bit slower.

What slows down a Python program?

If your Python code runs too fast, a call to time. sleep() is a simple way to slow down your code.

Why is Ruby slow?

Ruby is an interpreted language and interpreted languages will tend to be slower than compiled ones. Ruby uses garbage collection (though C#, which also uses garbage collection, comes out two orders of magnitude ahead of Ruby, Python, PHP etc. in the more algorithmic, less memory-allocation-intensive benchmarks above)


2 Answers

The recursion efficiency of python is the cause of this overhead. See this article for much more detail. The above solutions that solve this iteratively are better for python since they do not incur the function call overhead recursion does. My assumption about ruby would be that it is clearly optimizing the code while python is not. Again, that article goes into a lot detail about this using a nearly identical fib function.

like image 145
dcolish Avatar answered Sep 30 '22 19:09

dcolish


So for this code, Python is a bit more than two times slower than Ruby. Probably for other codes, Python will be faster than Ruby.

Your implementation of fib() has exponential run time. This can easily be avoided by using a loop. Python example:

a, b = 1, 1
for i in range(35):
    a, b = b, a+b
print b
like image 38
Sven Marnach Avatar answered Sep 30 '22 17:09

Sven Marnach