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))
posted on 2019-01-08 14:38  hailuo  阅读(422)  评论(0编辑  收藏  举报