这段python代码有什么问题吗,为什么它与ruby相比运行这么慢? [英] Is there something wrong with this python code, why does it run so slow compared to ruby?

查看:53
本文介绍了这段python代码有什么问题吗,为什么它与ruby相比运行这么慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对比较ruby速度与python感兴趣,因此我进行了最简单的递归计算,即打印斐波那契序列.

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

这是python代码

#!/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

这是红宝石代码

#!/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

那是红宝石,现在python2.7给出了

thats for ruby, now python2.7 gives

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

怎么了?

推荐答案

python的递归效率是造成此开销的原因.有关更多详细信息,请参见本文.上面的迭代解决方案对于python更好,因为它们不会产生函数调用开销递归.我对ruby的假设是,它很明显在优化代码,而python不是.再次,该文章使用几乎相同的fib函数对此进行了详细介绍.

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.

这篇关于这段python代码有什么问题吗,为什么它与ruby相比运行这么慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆