zoukankan      html  css  js  c++  java
  • python用装饰器实现缓存函数执行结果

    根据调用的函数名和调用的参数,对函数的结果进行缓存,下次执行的时候就不用重复计算

     
    可以用装饰器来实现
     
    import time
    import hashlib
    import pickle
     
    cache = {}
     
    def is_obsolete(entry,duration):
        d = time.time()-entry['time']
        return d>duration
       
    def compute_key(function,args,kwargs):
        key = pickle.dumps((function.func_name,args,kwargs))
        return hashlib.sha1(key).hexdigest()
     
    def memoize(duration=10):
        def _memorize(function):
            def __memorize(*args,**kwargs):
                key = compute_key(function,args,kwargs)
               
                if key in cache and not is_obsolete(cache[key],duration):
                    print 'we got a winner'
                    return cache[key][ 'value']
               
                result = function(*args,**kwargs)
                cache[key] = { 'value':result, 'time':time.time()}
                return result
            return __memorize
        return _memorize
    这里memoize就是一个装饰器,duration是缓存过期时间。compute_key函数合并调用的函数的名称、参数并计算出key。
    函数执行的结果result缓存在cache[key]中
     
    @memoize()
    def complex(a,b):
        time.sleep(2)
        return a+b 
    执行结果:
     
    可以看到函数成功缓存,如果把@memoize()改成@memoize(2),缓存时间就改成2秒了
     
    例程来自《Python高级编程》
  • 相关阅读:
    LVDS汇总
    smtp模块+Gmail搭建邮件发送功能
    网站建立(杂)
    xampp部署elgg
    转xampp 访问出现New XAMPP security concept
    FPGA参考电源
    android开发环境搭建问题
    cadence仿真前电路板设置(转)
    cadence串扰仿真 (转)
    cadence约束管理器总体设置 (转)
  • 原文地址:https://www.cnblogs.com/amghost/p/3572128.html
Copyright © 2011-2022 走看看