gpt4 book ai didi

python - 为什么 Python 2.7 比 3.2 快?

转载 作者:行者123 更新时间:2023-11-28 21:54:54 25 4
gpt4 key购买 nike

我编写了以下程序作为 Project Euler 问题 12 的解决方案,但在 Python 2.7 中需要 6.62 秒,在 Python 3.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 表示,除了更精确的时间安排之外,一个原因可能是不起眼的 /,其 definition changed Python 版本之间:

python 2.7:

>>> 5/2
2
>>> from __future__ import division
>>> 5/2
2.5

python 3.0:

>>> 5/2
2.5
>>> 5//2
2

使用 from __future__ 语句为 Python 2 重试计时。

关于python - 为什么 Python 2.7 比 3.2 快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23426756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com