为什么这个脚本在python3中花费的时间比python2多?

时间:2013-11-13 17:39:33

标签: python python-2.7 python-3.3

我写了这个脚本来确定第一个包含500多个因子的三角数(项目euler问题)并在python2.7和python3.3上运行它。我希望它们或多或少同时使用,但python3占用的时间是python2.7的两倍多。这背后的原因可能是什么?

    def highest_power(integer,prime):
        i=0
        while integer%prime**i==0:
            i+=1
        return i-1

    def n_factors(integer):
        number_of_factors=1
        start=2
        while integer>1 and integer>=start:
            number_of_factors=number_of_factors*(highest_power(integer,start)+1)
            integer=integer/start**highest_power(integer,start)
            start+=1
        return number_of_factors

    def main(number_of_factors):
        number_of_factors_list=[1,1] # Initialized with number of factors for m=1 and 2
        m=3
        while number_of_factors_list[-1]*number_of_factors_list[-2]<number_of_factors:
            if m%2!=0:
               number_of_factors_list.append(n_factors(m))
            elif m%2==0:
                number_of_factors_list.append(n_factors(m/2))
            m+=1
       return (m-2)*(m-1)/2

    if __name__=='__main__':
        print(main(500))

以下是他们的时间

   $ time python2 script.py
   real 0m12.787s
   user 0m12.788s
   sys  0m0.000s

   $ time python3 script.py
   real 0m27.738s
   user 0m27.739s
   sys  0m0.000s

我在ubuntu 13.10 64位上运行它,使用python2.7和python3.3的预编译二进制文件。

1 个答案:

答案 0 :(得分:3)

您在Python 2中使用整数除法,在Python 3中使用浮点除法。查看是否添加

from __future__ import division

到脚本会增加Python 2下的运行时。