Skip to content

Instantly share code, notes, and snippets.

@theMagicalKarp
Created July 31, 2013 21:39
Show Gist options
  • Save theMagicalKarp/6126429 to your computer and use it in GitHub Desktop.
Save theMagicalKarp/6126429 to your computer and use it in GitHub Desktop.
This is a simple python decorator to cache a functions value by input.
import cPickle
def memoize(original_function, function_cache={}):
try:
cache = function_cache[original_function]
except KeyError:
cache = function_cache[original_function] = {}
def check_cache(*args, **kwargs):
hashed_kwargs = cPickle.dumps(kwargs)
try:
return cache[args, hashed_kwargs]
except KeyError:
cache[args, hashed_kwargs] = original_function(*args, **kwargs)
return cache[args, hashed_kwargs]
return check_cache
# running example and performance comparison with the recursive fibonacci sequence
import timeit
@memoize
def memo_fib(n):
if n == 0: return 0
elif n == 1: return 1
else: return memo_fib(n-1) + memo_fib(n-2)
def fib(n):
if n == 0: return 0
elif n == 1: return 1
else: return fib(n-1) + fib(n-2)
print timeit.Timer("memo_fib(30)",
setup="from __main__ import memo_fib").timeit(number=1)
print timeit.Timer("fib(30)",
setup="from __main__ import fib").timeit(number=1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment