Python 3:我的修饰函数运行两次
我有一些简单的斐波那契序列函数,我正在使用Travis CI/Docker进行单元测试和构建: fib_recursive.py:Python 3:我的修饰函数运行两次,python,python-3.x,function,Python,Python 3.x,Function,我有一些简单的斐波那契序列函数,我正在使用Travis CI/Docker进行单元测试和构建: fib_recursive.py: from fib.fib import benchmark, fib_rec_memo @benchmark def print_fib(n): for x in range(0, n): print(fib_rec_memo(x)) print_fib(100) 以下是fib.fib导入源代码: from time import ti
from fib.fib import benchmark, fib_rec_memo
@benchmark
def print_fib(n):
for x in range(0, n):
print(fib_rec_memo(x))
print_fib(100)
以下是fib.fib导入源代码:
from time import time
from functools import wraps
def benchmark(func):
@wraps(func)
def wrapper(*args, **kwargs):
t = time()
func(*args, **kwargs)
print(func.__name__, 'took:', time() - t)
return func(*args, **kwargs)
return wrapper
def fib_rec_memo(n, hash = {0:1, 1:1}):
if n not in hash:
hash[n] = fib_rec_memo(n-1) + fib_rec_memo(n-2)
return hash[n]
@benchmark
def fib_standard(num):
a, b = 0, 1
c = []
while a < num: # First iteration:
c.append(a) # yield 0 to start with and then
a, b = b, a + b # a will now be 1, and b will also be 1, (0 + 1)
return c
有人知道为什么吗
谢谢。您在
包装器中调用装饰函数两次
函数:
func(*args, **kwargs) # here ...
print(func.__name__, 'took:', time() - t)
return func(*args, **kwargs) # ... and here again
通过将结果存储到变量并在计时输出后返回存储的结果,可以避免这种情况:
rval = func(*args, **kwargs) # call it once and store result ...
print(func.__name__, 'took:', time() - t)
return rval # ... then return result
“出于某种原因”——因为你真的叫了两次?
rval = func(*args, **kwargs) # call it once and store result ...
print(func.__name__, 'took:', time() - t)
return rval # ... then return result