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)

 

未完待續


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM