Last active
February 27, 2024 17:36
-
-
Save hughdbrown/bf5c63792d5f912a162bf012fb6b4527 to your computer and use it in GitHub Desktop.
Minimal lru_cache implementation for python 2.7
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
thanks