python 缓存技术(cache)

1,Memoizing(自动缓存)

  话不多说,看个例子。

import time,hashlib,pickle

cache = {}

def is_obsolete(entry,duration):
    return time.time() - entry['time'] > duration

def compute_key(function,args,kw):
    key = pickle.dumps((function.func_name,args,kw))
    return hashlib.sha1(key).hexdigest()

def memoize(duration=10):
    def _memoize(function):
        def __memoize(*args,**kw):
            key = compute_key(function,args,kw)
            
            #if has it?
            if (key in cache and not is_obsolete(cache[key],duration)):
                print 'we got a winner'
                return cache['key']['value']
            
            #calc
            result = function(*args,**kw)
            cache[key] = {'value':result,'time':time.time()}
            return result
        return __memoize
    return _memoize

  sha hash 键值使用已排序的参数值建立,该结果将保存在一个全局字典中。hash使用一个pickle来建立,这是冻结所有作为参数传递的对象状态,以确保所有的参数均为良好候选者的一个快键方式。

  duration用于在上次函数调用之后,使存在太久的缓存值失效。

  看结果:

if __name__ == '__main__':
#    @memoize()
#    def complex_stuff(a,b):
#        return a + b
#    
#    print complex_stuff(2, 2)
#    time.sleep(1)
#    print complex_stuff(2, 2)
    
    @memoize(1) #1秒之后令缓存失效
    def complex_stuff(a,b):
        return a + b
    print complex_stuff(2, 2)
    time.sleep(2)
    print complex_stuff(2, 2)

 

未完待续

posted @ 2013-05-14 14:36  jiezhao  阅读(6568)  评论(0编辑  收藏  举报