简体   繁体   中英

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. 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?

Apart from more precise timing, that Martijn Pieters suggests, one reason might be the humble / , whose definition changed between Python versions:

Python 2.7:

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

Python 3.0:

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

Re-try your timing with the from __future__ statement for the Python 2 case.

The Python3 int type was formerly the Python2 long type. Longs are slower than ints. Python is optimized for simplicity not speed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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