[英]Why does this code behave differently in Python3.1 than in Python2.6?
[英]Why is Python 3.1 slower than 2.6 for this code?
考虑以下代码(从此处开始 ,测试数量有所增加):
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.73663210869
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
有谁知道为什么这段代码在Python 3.1上运行慢三倍?
我使用“ /”版本从2.5、2.6、2.7和3.1(Windows XP SP2)稳定地减少了时间。 通过//,3.1倍显着小于2.X倍,例如“范数”从6.35(py2.7)降至3.62(py3.1)。
请注意,在2.x版本中,有整数(32位或64位机器字)和长整数(可变长度)。 在3.x中,long已重命名为int,而int消失了。 我的猜测是,从long转换为float可能导致使用/的额外时间。
无论如何,一个更好的“ Alt”版本将从以下代码开始:
high = 1
highpown = 1
while highpown < x:
high <<= 1
highpown <<= n
//
运算符在python 2和3中都执行整数除法(或下限除法),而/
运算符在python 2中给定整数操作数执行下限除法,在python 3中给定任何操作数执行真除法。
尝试将/
运算符替换为//
运算符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.