Python / Cache / lru_cache

functools lru_cache

By Marcelo Fernandes Aug 25, 2017

functools.lru_cache (Least Recently Used Cache)

Testing using the common Fibonacci Example


from timeit import timeit


normal_setup = """
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)
"""

cache_setup = """
from functools import lru_cache

@lru_cache(maxsize=128)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)
"""

operation = """
[fib(n) for n in range(16)]
"""

normal_time = timeit(stmt=operation, setup=normal_setup, number=1000)
cached_time = timeit(stmt=operation, setup=cache_setup, number=1000)

normal_time, cached_time
# (0.5503400499997042, 0.0017666910002844816)



Notes


References

link 1