Skip to content

Instantly share code, notes, and snippets.

@wilsonfreitas
Forked from hughdbrown/lru_cache.py
Created September 20, 2022 13:25
Show Gist options
  • Save wilsonfreitas/f381864601f8ec4dd855ce50ec28621c to your computer and use it in GitHub Desktop.
Save wilsonfreitas/f381864601f8ec4dd855ce50ec28621c to your computer and use it in GitHub Desktop.
Minimal lru_cache implementation for python 2.7
from functools import wraps
try:
from functools import lru_cache
except ImportError:
def lru_cache(user_function):
cache = {}
@wraps(user_function)
def wrapper(*args):
key = tuple(args)
if key not in cache:
cache[key] = user_function(*args)
return cache[key]
return wrapper
def fib(n):
if n in (1, 2):
return 1
else:
return fib(n - 2) + fib(n - 1)
@lru_cache
def fib2(n):
if n in (1, 2):
return 1
else:
return fib2(n - 2) + fib2(n - 1)
from datetime import datetime
def time_fn(fn, *args):
s = datetime.now()
print(fn(*args))
e = datetime.now()
print(e - s)
time_fn(fib, 40)
time_fn(fib2, 40)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment