【发布时间】:2022-01-01 06:18:45
【问题描述】:
我正在尝试使用我的 timer_func 装饰器来记录斐波那契函数的处理时间。但看起来装饰器正在记录多次:
def timer_func(func):
def inner_func(*args):
t1 = perf_counter()
res = func(*args)
t2 = perf_counter()
logging.log(logging.INFO, f"Done in {t2 - t1} Seconds!")
return res
return inner_func
@timer_func
def fibonacci(x: int):
if x > 2:
return fibonacci(x - 1) + fibonacci(x - 2)
elif x == 1 or x == 2:
return 1
r = timer_func(fibonacci)(5)
print("Fibonacci %d of is %d" % (5, r))
输出:
Done in 7.269991328939795e-07 Seconds!
Done in 7.840008038328961e-07 Seconds!
Done in 0.00013806700007990003 Seconds!
Done in 0.0006901449996803422 Seconds!
【问题讨论】:
-
可能是因为你多次调用它?
-
你还要装饰两次
-
创建一个包装器函数,它只调用未修饰的 fib 函数并修饰包装器。
-
这是一个练习吗?因为否则 Python 已经有一个用于计时函数的装饰器。见stackoverflow.com/q/7370801/839733
-
@AbhijitSarkar 是的。我不想用那个