嵌套函数的性能开销是多少? [英] What is the performance overhead of nested functions?

查看:96
本文介绍了嵌套函数的性能开销是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,可以像这样嵌套函数:

  def do_something():
def helper ():
....
....

除非Python每次使用 do_something 时,都必须重新创建 helper 。实际上是否有这样的性能冲击,而不是在主体之外创建辅助函数,如果是,它有多好?

解决方案 div>

是的,在主函数中声明一个助手比单独声明它们要慢一些:

  ### test_nested。 py ### 
import timeit
def foo():
def bar():
pass
pass
print(timeit.timeit(foo (),setup =from __main__ import foo))

### test_flat.py ###
导入时间
def foo():
通过
def bar():
传递
print(timeit.timeit(foo(),setup =from __main__ import foo,bar))


### Shell ###
✗python3 ./test_flat.py
0.42562198638916016
✗python3 ./test_nested.py
0.5836758613586426
code>

这是大约30%的放缓。请记住,在这个微不足道的案例中,创建和调用函数都是解释器所做的。在任何实际使用中,差异都会小得多。


In Python, it is possible to nest functions like this:

def do_something():
    def helper():
        ....
    ....

Unless Python handles this case more smartly, helper has to be created anew every time do_something is used. Is there in fact a performance hit from doing this instead of creating the helper function outside of the main one and if yes, how great is it?

解决方案

Yes, declaring a helper inside the main function is slower that declaring them separately:

### test_nested.py ###
import timeit
def foo():
    def bar():
        pass
    pass
print(timeit.timeit("foo()", setup="from __main__ import foo"))

### test_flat.py ###
import timeit
def foo():
    pass
def bar():
    pass
print(timeit.timeit("foo()", setup="from __main__ import foo, bar"))


### Shell ###
✗ python3 ./test_flat.py
0.42562198638916016
✗ python3 ./test_nested.py
0.5836758613586426

That's a slowdown of about 30%. Remember that in this trivial case creating and calling functions is all the interpreter does. In any real usage the difference will be much less.

这篇关于嵌套函数的性能开销是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆