为什么Python2.7比3.2快?

2024-09-25 08:34:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了以下程序作为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速度较慢吗?在


Tags: inimport程序iftimedefarg解决方案
2条回答

Martijn Pieters认为,除了更精确的计时之外,一个原因可能是不起眼的/,其{a1}在Python版本之间:

Python语言:

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

Python 3.0:

^{pr2}$

对于Python2案例,请使用from __future__语句重新尝试计时。在

Python3 int类型以前是Python2 long类型。long比int慢。Python是为了简单而不是速度而优化的。在

相关问题 更多 >