特定代码行的类似于装饰器的语法 [英] Decorator-like syntax for a specific line of code
问题描述
Linked topic (but not duplicate): Decorator to time specific lines of the code instead of whole method?
我知道Python函数通常使用装饰器.
I know how decorators are usually used for Python functions.
单行代码是否有类似的概念/语法?
示例:使用
def measuretime(lineofcode):
start = time.time()
lineofcode()
print time.time() - start
然后
@measuretime
im = Image.open(BytesIO(base64.b64decode(data)))
将被解释为
start = time.time()
im = Image.open(BytesIO(base64.b64decode(data)))
print time.time() - start
注意:
-
我知道像这样测量执行时间并不是最佳选择,最好使用
timeit
等,但这只是一个随机示例,它显示了我正在寻找的内容(单行代码的修饰符)
I know measuring execution time like this is not optimal, it's better to use
timeit
, etc. but it's just a random example to show what I'm looking for (decorators for single lines of code)
我正在寻找1或2行代码的解决方案(当然是+函数的定义).如果解决方案需要两行以上的代码(即,比 @measuretime
之类的代码要多),那么最好放弃并照常做:
I'm looking for a 1 or 2 lines of code solution (+ definition of the function of course). If the solution takes more than 2 lines of code (i.e. more than something like @measuretime
), then it's probably better to give up and just do the normal:
start = time.time()
im = Image.open(BytesIO(base64.b64decode(data)))
print time.time() - start
推荐答案
If you want to do stuff before and after a line of code, a context manager would be appropriate:
from contextlib import contextmanager
import time
@contextmanager
def measuretime():
start = time.time()
try:
yield
finally:
print(time.time() - start)
with measuretime():
do_stuff()
这篇关于特定代码行的类似于装饰器的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!