一位同事向我指出,with
语句可能很慢。因此,我进行了测量,实际上从contextmanager
函数获取值的时间比在Python 2.7中从生成器获取值的时间要长20倍,而在PyPy 2.6中则需要200倍。
为什么会这样呢?是否可以重写contextlib.contextmanager()
以使其运行更快?
供引用:
def value_from_generator():
def inner(): yield 1
value, = inner()
return value
def value_from_with():
@contextmanager
def inner(): yield 1
with inner() as value:
return value
和时间:
$ python -m timeit 'value_from_generator()'
10000000 loops, best of 3: 0.169 usec per loop
$ python -m timeit 'value_from_with()'
100000 loops, best of 3: 3.04 usec per loop
最佳答案
使用探查器和contextlib的源,我发现:
value_from_with:
ncalls tottime cumtime filename:lineno(function)
1000000 1.415 4.802 value_from_with # 1sec more than value_from_generator, likely caused by with statement
1000000 1.115 1.258 contextlib.py:37(__init__) # better doc string of context manager instance
1000000 0.656 0.976 contextlib.py:63(__exit__) # optional exception handling
1000000 0.575 1.833 contextlib.py:124(helper) # "wrapped" in decorator
2000000 0.402 0.604 {built-in method next} # why it's so expensive?
1000000 0.293 0.578 contextlib.py:57(__enter__) # a next() call to the generator in try&except block (just for error msg)
2000000 0.203 0.203 inner1
1000000 0.143 0.143 {built-in method getattr} # better doc string, called by __init__
value_from_generator:
ncalls tottime cumtime filename:lineno(function)
1000000 0.416 0.546 value_from_generator
2000000 0.130 0.130 inner2
它告诉我们:从generator拆包比使用next()更快。
函数调用很昂贵;异常处理是昂贵的...因此比较是不公平的,并且此配置文件只是出于娱乐目的。
它还告诉我们,每次执行“with”块时,都会创建一个上下文管理器实例(几乎不可避免)。除此之外,
contextmanager
还做了一些工作来说服我们。如果您确实想对其进行优化,则可以编写一个上下文管理器类,而不是使用装饰器。概要文件代码:
def inner1(): yield 1
def value_from_generator():
value, = inner1()
return value
# inner should not be created again and again
@contextmanager
def inner2(): yield 1
def value_from_with():
with inner2() as value:
return value