小编wyf*_*yfo的帖子

Python 中嵌套函数的性能开销

在 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(): …
Run Code Online (Sandbox Code Playgroud)

python optimization performance python-3.x

17
推荐指数
1
解决办法
228
查看次数

标签 统计

optimization ×1

performance ×1

python ×1

python-3.x ×1