Python functools lru_cache

Content:

Saw a post about on LinkedIn.

In some cases it can have a huge impact.

import time

def fib(n):
    if n < 2:
        return n
    else:
        return fib(n - 1) + fib(n - 2)

t1 = time.time()
res = fib(42)
t2 = time.time()
print('res=%d dt=%.3f' % (res, t2 - t1))
python fib.py
res=267914296 dt=49.534
from functools import lru_cache
import time

@lru_cache(100)
def fib(n):
    if n < 2:
        return n
    else:
        return fib(n - 1) + fib(n - 2)

t1 = time.time()
res = fib(42)
t2 = time.time()
print('res=%d dt=%.3f' % (res, t2 - t1))

python fibc.py
res=267914296 dt=0.001

This example is of course extreme. But it seems obvious that even more common functions may provide significant performance improvements.

Comments: