2007-01-22

 

Python VS Ruby

今天突发奇想,把Python做了一个小比较,代码来自ruby的计算PI的例子,我以算10000位为标准,比较了一下二者的效率。
pi.rb
k, a, b, a1, b1 = 2, 4, 1, 12, 4
n=10000
time1 = Time.new
while n>0
    
# Next approximation
    p, q, k = k*k, 2*k+1, k+1
    a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
    
# Print common digits
    d = a / b
    d1 = a1 / b1
    while d == d1
        
#print d
        #$stdout.flush

        a, a1 = 10*(a%b), 10*(a1%b1)
        d, d1 = a/b, a1/b1
    end
    n-=1
end
time2 = Time.new

print (time2-time1).to_f

pi.py

from time import clock
k, a, b, a1, b1 = 2, 4, 1, 12, 4
time = clock()
n=10000
while n>0:
    
# Next approximation
    p, q, k = k*k, 2*k+1, k+1
    a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
   
 # Print common digits
    d = a / b
    d1 = a1 / b1
    while d == d1:
        
#print d,
        a, a1 = 10*(a%b), 10*(a1%b1)
        d, d1 = a/b, a1/b1
    n-=1
print clock() - time

为了屏蔽IO操作对效率的影响,注释调了输出语句。
结果如下:
>ruby pi.rb
12.985
>Exit code: 0

>pythonw -u "pi.py"
12.405357027
>Exit code: 0

还是Python略胜一筹。








Comments: 发表评论



<< Home

This page is powered by Blogger. Isn't yours?