【发布时间】:2021-12-31 16:49:17
【问题描述】:
我有以下上下文管理器和装饰器来为任何给定的函数或代码块计时:
import time
from contextlib import ContextDecorator
class timer(ContextDecorator):
def __init__(self, label: str):
self.label = label
def __enter__(self):
self.start_time = time.perf_counter()
return self
def __exit__(self, *exc):
net_time = time.perf_counter() - self.start_time
print(f"{self.label} took {net_time:.1f} seconds")
return False
您可以将其用作上下文管理器:
with timer("my code block"):
time.sleep(2)
# my code block took 2.0 seconds
您也可以将其用作装饰器:
@timer("my_func")
def my_func():
time.sleep(3)
my_func()
# my_func took 3.0 seconds
我唯一不喜欢的是在用作装饰器时必须手动将函数名称作为label 传递。如果没有传递标签,我希望装饰器自动使用函数名称:
@timer()
def my_func():
time.sleep(3)
my_func()
# my_func took 3.0 seconds
有什么办法吗?
【问题讨论】:
标签: python decorator python-decorators