我正在用 python 实现缓存服务。到目前为止,我正在使用一个简单的字典。我想做的是计算命中次数(键检索存储值的次数)。 Python 内置 dict 没有这种可能性(据我所知)。我搜索了“python dictionary count”并找到了 Counter
(也在 stackoverflow 上),但我猜这不能满足我的要求。我不需要计算已经存在的东西。我需要增加来自外部的东西。而且我认为存储另一个仅包含命中计数的字典并不是我可以获得的最佳数据结构:)
您有什么想法可以有效地做到这一点吗?
最佳答案
对于替代方法,如果您使用的是 Python 3(或者愿意将 this module 添加到您的 Python 2 项目,它的界面略有不同),我强烈推荐 lru_cache
装饰器。
查看文档 here .例如,这段代码:
from functools import lru_cache
@lru_cache(maxsize=32)
def meth(a, b):
print("Taking some time", a, b)
return a + b
print(meth(2, 3))
print(meth(2, 4))
print(meth(2, 3))
...将输出:
Taking some time 2 3
5
Taking some time 2 4
6
5 <--- Notice that this function result is cached
根据文档,您可以使用 meth.cache_info()
获取命中和未命中的次数,并使用 meth.cache_clear()
清除缓存。
关于python缓存字典 - 计算命中次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19443431/