Skip to content

Instantly share code, notes, and snippets.

@sanpingz
Last active December 16, 2015 06:48
Show Gist options
  • Save sanpingz/5393694 to your computer and use it in GitHub Desktop.
Save sanpingz/5393694 to your computer and use it in GitHub Desktop.
装饰器实现的函数缓存器
import time
def timer(func):
def newFunc(*pargs, **kargs):
start = time.time()
back = func(*pargs, **kargs)
print "Timer: %.2fs" % (time.time()-start)
return back
return newFunc
class FuncCache:
def __init__(self, func):
self.func = func
self.cache = {}
self.num = 0
def cached(self, *pargs, **kargs):
result = None
if self.cache:
for key in self.cache.keys():
cache = self.cache[key]
if len(cache) == 3 and set(cache[0]) == set(pargs) and cache[1] == kargs:
result = cache[-1]
break
return result
def __call__(self, *pargs, **kargs):
result = self.cached(*pargs, **kargs)
if result == None:
result = self.func(*pargs, **kargs)
self.num += 1
self.cache[self.num] = [pargs, kargs, result]
print 'calcing'
return result
@timer
@FuncCache
def calc(*pargs):
time.sleep(3)
return sum(pargs)
if __name__ == '__main__':
print calc(*range(100000))
print calc(*range(100000))
print calc(*range(1000000))
print calc(*range(100000))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment