Skip to content

Instantly share code, notes, and snippets.

@itsyarkee
Created September 30, 2013 03:57
Show Gist options
  • Save itsyarkee/6759213 to your computer and use it in GitHub Desktop.
Save itsyarkee/6759213 to your computer and use it in GitHub Desktop.
Use decorate to maintain a memory cache.
#-*-coding:utf-8-*-
"""
Use decorate to maintain a memory cache.
"""
def cache_c(fn):
cache = {}
miss = None
def wrapper(*args, **kwargs):
result = cache.get(args, miss)
if result is miss:
result = fn(*args, **kwargs)
cache[args] = result
return result
return wrapper
@cache_c
def fib_cache(n):
if n < 2:
return n
return fib_cache(n-1) + fib_cache(n-2)
def fib_uncache(n):
if n < 2:
return n
return fib_uncache(n-1) + fib_uncache(n-2)
def test():
n = 30
import time
begin = time.time()
fib_cache(n)
end = time.time()
print("cost time:%f" % (end - begin))
begin = time.time()
fib_uncache(n)
end = time.time()
print("cost time:%f" % (end - begin))
if __name__ == '__main__':
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment