-
-
Save wilsonfreitas/f381864601f8ec4dd855ce50ec28621c 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