简体   繁体   English

为什么Python 2.7比3.2快?

[英]Why is Python 2.7 faster than 3.2?

I wrote the following program as a solution to Project Euler problem 12 but in Python 2.7 it takes 6.62 seconds and in Python 3.2 it takes 10.21 seconds. 我编写了以下程序作为Project Euler问题12的解决方案,但在Python 2.7中花费了6.62秒,而在Python 3.2中花费了10.21秒。 Surely it should be the other way round! 当然应该反过来!

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()

Does anyone know why the later version of Python is slower? 有谁知道为什么更高版本的Python较慢?

Apart from more precise timing, that Martijn Pieters suggests, one reason might be the humble / , whose definition changed between Python versions: Martijn Pieters建议,除了更精确的时间安排之外,原因之一可能是谦逊的/ ,其定义在Python版本之间有所不同:

Python 2.7: Python 2.7:

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

Python 3.0: Python 3.0:

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

Re-try your timing with the from __future__ statement for the Python 2 case. 对于Python 2案例,请使用from __future__语句重试计时。

The Python3 int type was formerly the Python2 long type. Python3 int类型以前是Python2 long类型。 Longs are slower than ints. 长整数比整数慢。 Python is optimized for simplicity not speed. Python是为简单而不是速度而优化的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM