考慮下面的代碼(從here,與試驗次數增加):爲什麼Python 3.1的代碼比2.6慢?
from timeit import Timer
def find_invpow(x,n):
"""Finds the integer component of the n'th root of x,
an integer such that y ** n <= x < (y + 1) ** n.
"""
high = 1
while high ** n < x:
high *= 2
low = high/2
while low < high:
mid = (low + high) // 2
if low < mid and mid**n < x:
low = mid
elif high > mid and mid**n > x:
high = mid
else:
return mid
return mid + 1
def find_invpowAlt(x,n):
"""Finds the integer component of the n'th root of x,
an integer such that y ** n <= x < (y + 1) ** n.
"""
low = 10 ** (len(str(x))/n)
high = low * 10
while low < high:
mid = (low + high) // 2
if low < mid and mid**n < x:
low = mid
elif high > mid and mid**n > x:
high = mid
else:
return mid
return mid + 1
x = 237734537465873465
n = 5
tests = 1000000
print "Norm", Timer('find_invpow(x,n)', 'from __main__ import find_invpow, x,n').timeit(number=tests)
print "Alt", Timer('find_invpowAlt(x,n)', 'from __main__ import find_invpowAlt, x,n').timeit(number=tests)
使用Python 2.6(Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) [GCC 4.4.3] on linux2
),報告的時間是:
Norm 9.869
Alt 9.53973197937
然而,在相同的機器上使用Python 3.1(Python 3.1.2 (r312:79147, Apr 15 2010, 15:35:48) [GCC 4.4.3] on linux2
),時間是:
Norm 28.4206559658
Alt 26.8007400036
有沒有人知道爲什麼這個鱈魚e在Python 3.1上運行速度慢三倍?
沒有攝製:python3.1比2.6快了30%左右我的機器上。 – SilentGhost 2010-07-11 09:45:08
謝謝。你在運行什麼操作系統?我在Ubuntu 10.04 64位上獲得了上述時間。 – user200783 2010-07-11 09:47:08
同一個系統的32位版本 – SilentGhost 2010-07-11 09:49:55