代码之家  ›  专栏  ›  技术社区  ›  user200783

为什么python3.1比2.6慢?

  •  5
  • user200783  · 技术社区  · 14 年前

    考虑以下代码(从 here ,随着测试次数的增加):

    from timeit import Timer
    
    def find_invpow(x,n):
        """Finds the integer component of the n'th root of x,
        an integer such that y ** n <= x < (y + 1) ** n.
        """
        high = 1
        while high ** n < x:
            high *= 2
        low = high/2
        while low < high:
            mid = (low + high) // 2
            if low < mid and mid**n < x:
                low = mid
            elif high > mid and mid**n > x:
                high = mid
            else:
                return mid
        return mid + 1
    
    def find_invpowAlt(x,n):
        """Finds the integer component of the n'th root of x,
        an integer such that y ** n <= x < (y + 1) ** n.
        """
        low = 10 ** (len(str(x)) / n)
        high = low * 10
        while low < high:
            mid = (low + high) // 2
            if low < mid and mid**n < x:
                low = mid
            elif high > mid and mid**n > x:
                high = mid
            else:
                return mid
        return mid + 1
    
    x = 237734537465873465
    n = 5
    tests = 1000000
    
    print "Norm", Timer('find_invpow(x,n)', 'from __main__ import find_invpow, x,n').timeit(number=tests)
    print "Alt", Timer('find_invpowAlt(x,n)', 'from __main__ import find_invpowAlt, x,n').timeit(number=tests)
    

    使用Python 2.6( Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) [GCC 4.4.3] on linux2 ),报道时间为:

    Norm 9.73663210869
    Alt 9.53973197937
    

    但是,在使用python3.1的同一台机器上( Python 3.1.2 (r312:79147, Apr 15 2010, 15:35:48) [GCC 4.4.3] on linux2 ),时间是:

    Norm 28.4206559658
    Alt 26.8007400036
    

    有人知道为什么这段代码在python3.1上运行慢了三倍吗?

    2 回复  |  直到 7 年前
        1
  •  3
  •   John Machin Santi    14 年前

    在任何情况下,更好的“Alt”版本都可以从以下代码开始:

    high = 1
    highpown = 1
    while highpown < x:
        high <<= 1
        highpown <<= n
    
        2
  •  2
  •   fmark    14 年前

    // 运算符在python2和python3中都执行整数除法(或楼层除法),而 / 运算符在给定整数操作数的python 2中执行底除法,在给定任何操作数的python 3中执行真除法。

    尝试更换 操作员和 接线员。