python 修饰递归函数

python decorating recursive function

我正在尝试使用我的 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!

每次调用 fibonacci 函数时都会发生日志。由于该函数是递归的,因此会被多次调用。

您需要制作具有装饰器并调用未装饰函数的函数的第二个版本。例如:

@timer_func
def fibonacci(x: int):
    return _fibonacci(x)


def _fibonacci(x: int):
    if x > 2:
        return _fibonacci(x - 1) + _fibonacci(x - 2)
    elif x == 1 or x == 2:
        return 1

即使在使用 @ 装饰函数之后,您仍然只是在装饰

r = fibonacci(5)

会做。