Created
August 11, 2013 05:04
-
-
Save mayli/6203472 to your computer and use it in GitHub Desktop.
My little cache demo
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
""" | |
My little cache demo | |
without cache | |
$ time python PythonPlay.py | |
14930352 | |
real 0m9.392s | |
user 0m9.266s | |
sys 0m0.077s | |
with cache | |
$ time python PythonPlay.py | |
14930352 | |
real 0m0.126s | |
user 0m0.046s | |
sys 0m0.062s | |
""" | |
CACHE_POOL={} | |
class cached(object): | |
def __init__(self, f, pool=CACHE_POOL): | |
self.f = f | |
self.pool = pool | |
def __call__(self, *args, **kwargs): | |
key = '#%s(%s, %s)'%(self.f.__name__, ','.join([repr(arg) for arg in args]), ','.join(['%s=%v'%(k,v) for k,v in kwargs.items()])) | |
if key in self.pool: | |
pass | |
else: | |
self.pool[key]=self.f(*args, **kwargs) | |
return self.pool[key] | |
@cached # the cache here | |
def fib(i,b=0): | |
if i==0: | |
return 1 | |
elif i==1: | |
return 1 | |
else: | |
return fib(i-1)+fib(i-2) | |
print fib(35,2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment