链接主题(但不重复):装饰器对代码的特定行而不是整个方法进行计时? https://stackoverflow.com/questions/30433910/decorator-to-time-specific-lines-of-the-code-instead-of-whole-method
我知道装饰器通常如何用于 Python 函数。
单行代码是否有类似的概念/语法?
示例:与
def measuretime(lineofcode):
start = time.time()
lineofcode()
print time.time() - start
then
@measuretime
im = Image.open(BytesIO(base64.b64decode(data)))
会被解释为
start = time.time()
im = Image.open(BytesIO(base64.b64decode(data)))
print time.time() - start
Notes:
-
我知道这样测量执行时间并不是最佳的,最好使用timeit https://stackoverflow.com/q/8220801/1422096等等,但这只是一个随机的例子来展示我正在寻找的东西(单行代码的装饰器)
-
我正在寻找 1 或 2 行代码解决方案(当然还有函数的定义)。如果解决方案需要超过 2 行代码(即超过类似@measuretime
),那么最好放弃并做正常的事情:
start = time.time()
im = Image.open(BytesIO(base64.b64decode(data)))
print time.time() - start
如果你想在一行代码之前和之后做一些事情,上下文管理器 https://www.python.org/dev/peps/pep-0343/将是适当的:
from contextlib import contextmanager
import time
@contextmanager
def measuretime():
start = time.time()
try:
yield
finally:
print(time.time() - start)
with measuretime():
do_stuff()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)