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

标签 python python-2.7 python-3.3

我编写此脚本以确定第一个具有超过 500 个因子的三角数(项目欧拉问题)并在 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 的预编译二进制文件。

最佳答案

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

from __future__ import division

脚本增加了 Python 2 下的运行时间。

关于python - 为什么这个脚本在 python3 中比在 python2 中花费更多的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19960648/

相关文章:

python - 使用 pandas GroupBy 检查组中的所有元素是否相等

python - 创建不同形状数组的对象数组时如何防止 numpy 广播

python - 我怎样才能只得到 plt.imread 的 rgb?

python - 从另一个列表中删除一个列表的成员

python - 为什么带参数的 object.__new__ 在 Python 2.x 中工作正常而不是在 Python 3.3+ 中工作?

python - Pygame,屏幕仅在退出pygame窗口时更新?

python - 提交带有 Mechanize HTTP 错误 500 的表单

Python 切片按相反顺序赋值不起作用!为什么?

python - 为特定列写带双引号的 csv 文件不起作用

python - Python 初学者 - 为什么我的 while 循环不起作用?