python – 嵌套函数的性能开销是多少?
发布时间:2020-12-20 11:24:28 所属栏目:Python 来源:网络整理
导读:参见英文答案 Is there an overhead when nesting functions in Python?????????????????????????????????????6个 在Python中,可以嵌套这样的函数: def do_something(): def helper(): .... .... 除非Python更巧妙地处理这种情况,否则每次使用do_something
参见英文答案 >
Is there an overhead when nesting functions in Python?????????????????????????????????????6个
在Python中,可以嵌套这样的函数: def do_something(): def helper(): .... .... 除非Python更巧妙地处理这种情况,否则每次使用do_something时都必须重新创建帮助程序.事实上,这样做会影响性能,而不是在主要功能之外创建辅助功能,如果是的话,它有多棒? 解决方法
是的,在main函数中声明一个帮助器的速度比单独声明它们要慢:
### 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 这是一个约30%的放缓.请记住,在这个简单的案例中,创建和调用函数都是解释器所做的.在任何实际使用中,差异将小得多. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |