簡體   English   中英

為什么Python 2.7比3.2快?

[英]Why is Python 2.7 faster than 3.2?

我編寫了以下程序作為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建議,除了更精確的時間安排之外,原因之一可能是謙遜的/ ,其定義在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

對於Python 2案例,請使用from __future__語句重試計時。

Python3 int類型以前是Python2 long類型。 長整數比整數慢。 Python是為簡單而不是速度而優化的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM