在Python中嵌套函数时是否存在开销?

时间:2011-10-20 17:14:57

标签: python function nested

在Python中,如果我在父函数中有子函数,那么每次调用父函数时,子函数是否已“初始化”(创建)?将函数嵌套在另一个函数中是否存在任何开销?

6 个答案:

答案 0 :(得分:37)

是的,每次都会创建一个新对象。它可能不是问题,除非你有一个紧凑的循环。分析将告诉您它是否有问题。

In [80]: def foo():
   ....:     def bar():
   ....:         pass
   ....:     return bar
   ....: 

In [81]: id(foo())
Out[81]: 29654024

In [82]: id(foo())
Out[82]: 29651384

答案 1 :(得分:37)

代码对象是预编译的,因此该部分没有开销。函数对象在每次调用时构建 - 它将函数名称绑定到代码对象,记录默认变量等。

执行摘要:这不是免费的。

>>> from dis import dis
>>> def foo():
        def bar():
                pass
        return bar

>>> dis(foo)
  2           0 LOAD_CONST               1 (<code object bar at 0x1017e2b30, file "<pyshell#5>", line 2>)
              3 MAKE_FUNCTION            0
              6 STORE_FAST               0 (bar)

  4           9 LOAD_FAST                0 (bar)
             12 RETURN_VALUE 

答案 2 :(得分:14)

有一个影响,但在大多数情况下,它是如此之小,你不应该担心它 - 大多数非平凡的应用程序可能已经有性能瓶颈,其影响比这个大几个数量级。担心代码的可读性和可重用性。

这里有一些代码比较了每次通过循环重新定义函数的性能,而不是重用预定义的函数。

import gc
from datetime import datetime

class StopWatch:
     def __init__(self, name):
         self.name = name

     def __enter__(self):
         gc.collect()
         self.start = datetime.now()

     def __exit__(self, type, value, traceback):
         elapsed = datetime.now()-self.start
         print '** Test "%s" took %s **' % (self.name, elapsed)

def foo():
     def bar():
          pass
     return bar

def bar2():
    pass

def foo2():
    return bar2

num_iterations = 1000000

with StopWatch('FunctionDefinedEachTime') as sw:
    result_foo = [foo() for i in range(num_iterations)]

with StopWatch('FunctionDefinedOnce') as sw:
    result_foo2 = [foo2() for i in range(num_iterations)]

当我在运行OS X Lion的Macbook Air上的Python 2.7中运行时,我得到:

** Test "FunctionDefinedEachTime" took 0:00:01.138531 **
** Test "FunctionDefinedOnce" took 0:00:00.270347 **

答案 3 :(得分:3)

我对此也很好奇,所以我决定弄明白这会产生多少开销。 TL; DR,答案并不多。

Python 3.5.2 (default, Nov 23 2017, 16:37:01) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from timeit import timeit
>>> def subfunc():
...     pass
... 
>>> def no_inner():
...     return subfunc()
... 
>>> def with_inner():
...     def s():
...         pass
...     return s()
... 
>>> timeit('[no_inner() for _ in range(1000000)]', setup='from __main__     import no_inner', number=1)
0.22971350199986773
>>> timeit('[with_inner() for _ in range(1000000)]', setup='from __main__ import with_inner', number=1)
0.2847519510000893

我的本​​能是查看百分比(with_inner慢了24%),但在这种情况下这个数字是误导的,因为我们实际上永远不会从外部函数返回内部函数的值,尤其是函数实际上什么都不做 在犯了这个错误之后,我决定将它与其他常见事物进行比较,以确定何时这样做并且无关紧要:

    >>> def no_inner():
    ...     a = {}
    ...     return subfunc()
    ... 
    >>> timeit('[no_inner() for _ in range(1000000)]', setup='from __main__ import no_inner', number=1)
    0.3099582109998664

看看这个,我们可以看到它比创建一个空字典(the fast way)花费的时间更少,所以如果你做任何非平凡的事情,这可能根本不重要。

答案 4 :(得分:1)

其他答案很棒,很好地回答了这个问题。我想补充一点,在python中使用for循环,生成函数等可以避免大多数内部函数。

考虑以下示例:

def foo():
    # I need to execute some function on two sets of arguments:
    argSet1 = (arg1, arg2, arg3, arg4)
    argSet2 = (arg1, arg2, arg3, arg4)

    # A Function could be executed on each set of args
    def bar(arg1, arg2, arg3, arg4):
        return (arg1 + arg2 + arg3 + arg4)

    total =  bar(argSet1)
    total += bar(argSet2)

    # Or a loop could be used on the argument sets
    total = 0
    for arg1, arg2, arg3, arg4 in [argSet1, argSet2]:
        total += arg1 + arg2 + arg3 + arg4

这个例子有点傻,但我希望你能看到我的观点。通常不需要内部功能。

答案 5 :(得分:0)

是的。这样可以启用闭包以及函数工厂。

闭包使内部函数在调用时记住其环境状态。

def generate_power(number):

    # Define the inner function ...
    def nth_power(power):
        return number ** power

    return nth_power

示例

>>> raise_two = generate_power(2)
>>> raise_three = generate_power(3)

>>> print(raise_two(3))
8
>>> print(raise_three(5))
243
"""