python函数通过lru_cache缓存加速

通过lru_cache缓存加速

  • 不加缓存
%%time
def fib(n):
    return(1 if n in [1, 2] else fib(n-1)+fib(n-2))
print(fib(35))
9227465
Wall time: 2.11 s
  • 加lru_cache缓存,递归快的一笔
%%time
from functools import lru_cache

# 加一个装饰器,不用自己打表缓存了
@lru_cache(10)
def fib(n):
    return(1 if n in [1, 2] else fib(n-1) + fib(n-2))
print(fib(350))
6254449428820551641549772190170184190608177514674331726439961915653414425
Wall time: 0 ns

你可能感兴趣的:(python,设计模式)