import time
def timer_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Function {func.__name__} took {end_time - start_time} seconds to execute")
return result
return wrapper
@timer_decorator
def example_function():
time.sleep(2)
print("Function is running")
example_function()
在这个示例中,timer_decorator是一个装饰器,它计算并打印example_function的执行时间。通过使用@timer_decorator语法糖,我们将装饰器应用到example_function上123。
装饰器的优势
代码复用:可以将通用功能提取到装饰器中,减少代码重复。
增强可读性:通过装饰器,可以清晰地看到哪些函数被增强了哪些功能。
分离关注点:将核心逻辑与辅助功能分离,保持代码的清晰和简洁。