# 一.递归函数的弊端


import time

#@lru_cache(20)
def fibonacci(n):
if n < 2:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)

t1 = time.time()
print(fibonacci(35))
t2 = time.time()
print(t2 - t1)  # 4.007285118103027
t1 = time.time()
print(fibonacci(36))
t2 = time.time()
print(t2 - t1)  # 6.479698419570923


# 二.用缓存优化递归函数


import time

def cache_decorator(func):
cache_dict = {}

def decorator(arg):
try:
return cache_dict[arg]
except KeyError:
return cache_dict.setdefault(arg, func(arg))
return decorator

@cache_decorator
def fibonacci(n):
if n < 2:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)

t1 = time.time()
print(fibonacci(35))
t2 = time.time()
print(t2 - t1)  # 0
t1 = time.time()
print(fibonacci(36))
t2 = time.time()
print(t2 - t1)  # 0



t1 = time.time()
print(fibonacci(300))
t2 = time.time()
print(t2 - t1)  # 0.001026153564453125
t1 = time.time()
print(fibonacci(301))
t2 = time.time()
print(t2 - t1)  # 0.0


# 三.lru_cache装饰器

maxsize参数设置缓存内存占用上限，其值应当设为2的幂，值为None时表示没有上限

typed参数设置表示不同参数类型的调用是否分别缓存，这个参数的意思是如果设置为True，那么fibonacci(5)和fibonacci(5.0)将分别缓存，不存为一个。

lru_cache的使用只需要将上面我们自定义的装饰器替换为 lru_cache(None,False)即可。

posted @ 2021-04-24 22:54  cloudolt  阅读(105)  评论(0编辑  收藏  举报