functools.lru_cache() 把重复计算的值缓存,对于经常调用的某个函数添加该装饰器
递归类的可以使用
import time
import functools
def clock(func):
@functools.wraps(func)
def clocked(*args, *kwargs):
t0 = time.time()
result = func(args, **kwargs)
elapsed = time.time() - t0
name = func.name
arg_lst = []
if args:
arg_lst.append(', '.join(repr(arg) for arg in args))
if kwargs:
pairs = ['%s=%r' % (k, w) for k, w in sorted(kwargs.items())]
arg_lst.append(', '.join(pairs))
arg_str = ', '.join(arg_lst)
print('[%0.8fs] %s(%s) -> %r ' % (elapsed, name, arg_str, result))
return result
return clocked
@functools.lru_cache() # ➊
@clock # ➋
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-2) + fibonacci(n-1)
if name=='main':
print(fibonacci(6))