【发布时间】:2018-12-07 05:17:37
【问题描述】:
链接主题(但不重复):Decorator to time specific lines of the code instead of whole method?
我知道装饰器通常如何用于 Python 函数。
单行代码是否有类似的概念/语法?
例子:用
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等,但这只是一个随机示例来展示我正在寻找的内容(单行代码的装饰器) -
我正在寻找 1 或 2 行代码解决方案(当然是函数的定义)。如果解决方案需要超过 2 行代码(即比
@measuretime之类的代码更多),那么最好放弃并正常执行:start = time.time() im = Image.open(BytesIO(base64.b64decode(data))) print time.time() - start
【问题讨论】:
-
为了测试?使用
jupyter和%timeit。 -
@Sraw 我已经在问题中提到了
timeit,而且我没有使用jupyter/ipython,而是在脚本模式下使用Python,即python script.py。
标签: python decorator python-decorators