我正在尝试理解如何使用python DiskCache包从有记忆的数据库调用中删除键。下面是一个简单的函数,它显示了我是如何记忆一个简单的函数调用的,它工作得很好,后续的调用运行得更快。
文档说我可以删除特定的键,但是我看不到使用memoize装饰器生成的键是什么
我已经猜到它类似于cache.pop(("__main__slowfunc",5)),虽然这不会抛出错误,但它不会从缓存中删除键。
from diskcache import FanoutCache
from pathlib import Path
import os
import time
local = Path(os.environ["AllUsersProfile"]) / "CacheTests"
cacheLocation = local / "cache"
cache = FanoutCache(cacheLocation, timeout=1)
@cache.memoize()
def slowfunc(iterations):
for i in range(0, iterations):
time.sleep(1)
iterations = 6
start = time.time()
slowfunc(iterations)
end = time.time()
print(f"Initial Call = {round(end-start,0)}s")感谢您的任何帮助。谢谢
发布于 2018-12-06 04:34:02
这是一个很好的问题,如果你的示例与磁盘缓存的源代码似乎所做的事情相匹配,那么它是如何不工作的,这真的很令人困惑。
我对这个例子做了一点扩展,看起来对我来说是这样的。看看这对你是否有效:
from diskcache import FanoutCache
from pathlib import Path
import os
import time
local = Path(os.environ["AllUsersProfile"]) / "CacheTests"
cacheLocation = local / "cache"
cache = FanoutCache(cacheLocation, timeout=1)
@cache.memoize()
def slowfunc(iterations):
print("Recalculating")
for i in range(0, iterations):
time.sleep(1)
iterations = 3
cache.delete(("__main__slowfunc", iterations))
start = time.time()
slowfunc(iterations)
end = time.time()
print(f"Initial Call = {round(end-start,0)}s")
start = time.time()
slowfunc(iterations)
end = time.time()
print(f"Subsequent Call = {round(end-start,0)}s")
cache.delete(("__main__slowfunc", iterations))
start = time.time()
slowfunc(iterations)
end = time.time()
print(f"After deletion = {round(end-start,0)}s")结果:
Recalculating
Initial Call = 3.0s
Subsequent Call = 0.0s
Recalculating
After deletion = 3.0s我试过用pop而不是delete,这也行得通
https://stackoverflow.com/questions/53592369
复制相似问题