import time import functools def clock(func): @functools.wraps(func)#还原被装饰函数的__name__和__doc__属性 def clocked(*args,**kwargs):#支持关键字参数 t0 = time.perf_counter() result = func(*args,**kwargs) elapsed = time.perf_counter()- 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(maxsize=128,typed = False) #把耗时的函数结果保存起来,避免传入相同的参数重新计算,typed=true,把浮点数和整数分开保存 @clock def fibonacci(n): if n <2: return n return fibonacci(n-2) + fibonacci(n-1) if __name__ == '__main__': print(fibonacci(30))