Python import X or from X import Y? (performance)

前端 未结 4 1365
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 03:39

If there is a library from which I\'m going to use at least two methods, is there any difference in performance or memory usage between the following?

from X         


        
4条回答
  •  隐瞒了意图╮
    2020-11-30 04:29

    It can matter if you are calling a function a lot of times in a loop (millions or more). Doing the double dictionary lookup will eventually accumulate. The example below shows a 20% increase.

    Times quoted are for Python 3.4 on a Win7 64 bit machine. (Change the range command to xrange for Python 2.7).

    This example is highly based on the book High Performance Python, although their third example of local function lookups being better no longer seemed to hold for me.

    import math
    from math import sin
    
    def tight_loop_slow(iterations):
        """
        >>> %timeit tight_loop_slow(10000000)
        1 loops, best of 3: 3.2 s per loop
        """
        result = 0
        for i in range(iterations):
            # this call to sin requires two dictionary lookups
            result += math.sin(i)
    
    def tight_loop_fast(iterations):
        """
        >>> %timeit tight_loop_fast(10000000)
        1 loops, best of 3: 2.56 s per loop
        """
        result = 0
        for i in range(iterations):
            # this call to sin only requires only one lookup
            result += sin(i)
    

提交回复
热议问题