python 使用缓存加快运算
from functools import lru_cache import time from functools import wraps def clock(func): @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 @lru_cache() @clock def fibonacci(n): if n < 2: return 1 return fibonacci(n-2) + fibonacci(n-1) if __name__=='__main__': print(fibonacci(6))
每天扫一扫,到店付款省钱!
动动小手支持一下作者,谢谢🙏