什么是装饰器,用装饰器记录函数运行时间
目录
下面是一个简单的例子,使用装饰器记录函数运行时间:
python
import time
def timer_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print("Function {} run time is: {}s".format(func.__name__, end_time - start_time))
return result
return wrapper
@timer_decorator
def long_running_func():
time.sleep(2)
print("Running the long running function.")
long_running_func()
这里调用 long_running_func() 后会输出:
Running the long running function. Function long_running_func run time is: 2.0027260208129883s 这个例子中,timer_decorator 是一个装饰器,它接受一个函数作为参数,返回一个新函数。 在这个例子里, @timer_decorator 将 long_running_func 函数传递给 timer_decorator, timer_decorator 返回 wrapper 函数,并将 wrapper 函数的名字替换为 long_running_func。 在 wrapper 中使用了 python 内置的 time 模块记录开始时间和结束时间, 然后输出函数运行时间。
这样就可以在不修改 long_running_func 的情况下记录函数运行时间。