lru cache和ttl cache缓存写法,装饰器写法
程序员文章站
2024-03-18 12:47:52
...
lru cache 缓存
def lru_cache(maxsize):
cache = {}
keys = []
def inner(func):
def wrapper(*arg, **kwd):
key = arg
for item in kwd.items():
key += item
if key in keys:
keys.remove(key)
keys.append(key)
else:
keys.append(key)
cache[key] = func(*arg, **kwd)
return cache[key]
return wrapper
return inner
ttl cache 缓存
import time
def ttl_cache(ttl):
def wrapper(func):
obj=object()
cache={}
cache_get=cache.get
def inner(*arg, **kwds):
key=arg
if kwds:
key += kwds.items()
result = cache_get(key, obj)
if result is not obj:
timeout, value = result
if timeout > time.time():
return value
value = func(*arg, **kwds)
cache[key] = (time.time() + ttl, value)
return value
return inner
return wrapper
上一篇: 折纸的不归路(13)
下一篇: Flutter 拓展之Color