计算代码运行时间--带有返回值的装饰器
示例代码
import time def cal_time(fn): """计算程序运行时间的函数""" def inner(): start_time = time.time() ret = fn() end_time = time.time() print("程序一共执行了%s" % (end_time - start_time) + '秒') return ret return inner @cal_time def func(): """带有返回值的求阶乘的函数""" x = 1 for i in range(1, 100000): x *= i print(x) return x result = func() # 相当于 func = cal_time(func) print(result) # 查看inner函数的返回值
运行结果: