我编写了以下程序作为ProjectEuler问题12的解决方案,但是在Python2.7中需要6.62秒,在Python3.2中需要10.21秒。当然应该是相反的!在
import time
def mainrun():
start = time.time()
divnum = 0
i = 0
trinum = 0
while divnum < 501:
i += 1
trinum += i
divnum = 0
#2nd arg outside - no diff to speed
for j in range(1, int(trinum**.5)+1):
if trinum % j == 0:
divnum += 1
if trinum / j != j:
divnum += 1
print(trinum, '\nDivisors:', divnum)
print('Solved in', round((time.time()-start),2), 'seconds.')
mainrun()
有人知道为什么后期版本的Python速度较慢吗?在
Martijn Pieters认为,除了更精确的计时之外,一个原因可能是不起眼的
/
,其{a1}在Python版本之间:Python语言:
Python 3.0:
^{pr2}$对于Python2案例,请使用
from __future__
语句重新尝试计时。在Python3 int类型以前是Python2 long类型。long比int慢。Python是为了简单而不是速度而优化的。在
相关问题 更多 >
编程相关推荐