python用装饰器实现缓存函数执行结果
2017-11-24 00:00
393 查看
摘要: 缓存装饰器
根据调用的函数名和调用的参数,对函数的结果进行缓存,下次执行的时候就不用重复计算
可以用装饰器来实现
这里memoize就是一个装饰器,duration是缓存过期时间。compute_key函数合并调用的函数的名称、参数并计算出key。
函数执行的结果result缓存在cache[key]中
执行结果:
输出:
3
we got a winner
3
可以看到函数成功缓存,如果把@memoize()改成@memoize(2),缓存时间就改成2秒了
根据调用的函数名和调用的参数,对函数的结果进行缓存,下次执行的时候就不用重复计算
可以用装饰器来实现
# encoding:utf-8 # usr/bin/python import time import hashlib import pickle from functools import wraps 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): @wraps(function) # update_wrapper维持被修饰函数属性不变 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
执行结果:
print complex(1, 2) print complex(1, 2)
输出:
3
we got a winner
3
可以看到函数成功缓存,如果把@memoize()改成@memoize(2),缓存时间就改成2秒了
相关文章推荐
- python用装饰器实现缓存函数执行结果
- python 基础——实现一个带缓存功能的函数
- Python使用装饰器和线程限制函数执行时间的方法
- python 限制函数执行时间,自己实现 timeout
- 如何实现函数执行完,但是结果不被系统回收?
- Python: 使用装饰器“@”取得函数执行时间
- 装饰器应用,Python模块学习之(__call__)实现准确计算函数运行时间
- python 知识点:反射 之 getattr()实现以字符串形式导入模块和执行函数
- python使用装饰器和线程限制函数执行时间的方法
- Python实现对一个函数应用多个装饰器的方法示例
- Python: 使用装饰器“@”取得函数执行时间
- python 函数结果缓存一段时间的装饰器
- python 实现远程主机执行命令函数
- python 例子: 实现动态加载类,并自动执行它定义的函数
- Python函数的周期性执行实现方法
- python multiprocessing进程执行自定义的函数,然后又返回结果
- 获取python文件中的特定函数执行结果
- js闭包的用途(匿名自执行函数,缓存,实现封装,实现面向对象)
- Python实现ssh登录执行shell命令并将结果写入mysql数据库
- ssh批量登录并执行命令的python实现代码