Python 中嵌套函数的性能开销

wyf*_*yfo 17 python optimization performance python-3.x

在 Python 3.9 中,嵌套函数比普通函数慢得多,在我的例子中大约是 10%。

from timeit import timeit

def f():
    return 0

def factory():
    def g():
        return 0

    return g

g = factory()

print(timeit("f()", globals=globals()))
#> 0.074835498
print(timeit("g()", globals=globals()))
#> 0.08470309999999998
Run Code Online (Sandbox Code Playgroud)

dis.dis显示相同的字节码,我发现的唯一区别是函数内部标志。确实,dis.show_code显示g有标志NESTED而f没有。

但是,可以删除标志,并且g速度与f.

import inspect
g.__code__ = g.__code__.replace(co_flags=g.__code__.co_flags ^ inspect.CO_NESTED)
print(timeit("f()", globals=globals()))
#> 0.07321161100000001
print(timeit("g()", globals=globals()))
#> 0.07439838800000001
Run Code Online (Sandbox Code Playgroud)

我试图查看 CPython 代码以了解CO_NESTED标志如何影响函数执行,但我一无所获。对这种相对于CO_NESTED标志的性能差异有什么解释吗?

编辑:删除CO_NESTED标志似乎也对函数执行没有影响,除了开销,即使它捕获了变量。

import inspect
global_var = 40
def factory():
    captured_var = 2
    def g():
        return global_var + captured_var
    return g
g = factory()
assert g() == 42

g.__code__ = g.__code__.replace(co_flags=g.__code__.co_flags ^ inspect.CO_NESTED)
assert g() == 42  # function still works as expected
Run Code Online (Sandbox Code Playgroud)

sop*_*ros 1

我可能是错的,但我认为差异来自于这样一个事实:它g可能会引用本地变量,factory因此需要访问两个作用域来进行任何变量查找:globals以及factory. factory保护这个额外的作用域(或合并来自和 的作用域)很可能globals是您观察到的开销的原因。发生这种情况的一个很好的提示是,如果您嵌套另一层函数:

def factory():
    def ff():
        def g():
            return 0

        return g
    return ff()

g = factory()  # please note that it is equivalent from the perspective of time measurement
Run Code Online (Sandbox Code Playgroud)

时间:

print(timeit("f()", globals=globals(), number=100000000))
# > 6.792911
print(timeit("g()", globals=globals(), number=100000000))
# > 7.8184555
Run Code Online (Sandbox Code Playgroud)

在你的第一个计时案例中,我得到+5,7%(你的数字是+13.5%),在我的第二个例子中:+15,1%。