對於我的一個類,我最近遇到了使用miller-rabin算法來確定20到29000之間素數的ruby和python實現。我很好奇爲什麼即使它們看起來是相同的實現, python代碼運行得非常快。我已經讀過python通常比ruby更快,但速度差別有多大?爲什麼python實現miller-rabin的速度比ruby快很多?
miller_rabin.rb
def miller_rabin(m,k)
t = (m-1)/2;
s = 1;
while(t%2==0)
t/=2
s+=1
end
for r in (0...k)
b = 0
b = rand(m) while b==0
prime = false
y = (b**t) % m
if(y ==1)
prime = true
end
for i in (0...s)
if y == (m-1)
prime = true
break
else
y = (y*y) % m
end
end
if not prime
return false
end
end
return true
end
count = 0
for j in (20..29000)
if(j%2==1 and miller_rabin(j,2))
count+=1
end
end
puts count
miller_rabin.py:
import math
import random
def miller_rabin(m, k):
s=1
t = (m-1)/2
while t%2 == 0:
t /= 2
s += 1
for r in range(0,k):
rand_num = random.randint(1,m-1)
y = pow(rand_num, t, m)
prime = False
if (y == 1):
prime = True
for i in range(0,s):
if (y == m-1):
prime = True
break
else:
y = (y*y)%m
if not prime:
return False
return True
count = 0
for j in range(20,29001):
if j%2==1 and miller_rabin(j,2):
count+=1
print count
當我測量每個用測量命令在Windows PowerShell中的執行時間,我得到如下:
Python 2.7:
Ticks:4874403
總毫秒數:487.4403
的Ruby 1.9.3:
蜱:682232430
總毫秒:68223.243
我將不勝感激任何見解誰能給我到爲什麼他們是如此巨大的差異
我只是分析Ruby代碼,看看是否顯示任何東西。 – 2013-04-07 20:06:07
請注意,您應該在Python 2中將'range'更改爲'xrange'。'range'不必要地*分配一個數字列表。 – user4815162342 2013-04-07 20:36:30