我使用记忆化来加快复杂函数 complexfunct()
的使用。
此函数将不同维度的 numpy.array
作为输入(它可以存储 5 到 15 个值)。
numpy.array
的每个值都属于一组 5 个值。
所以我的 complexfunct()
允许的输入数量非常大,不可能记住所有这些。
这就是为什么当我运行我的 jupyter notebook 时它崩溃了。
我正在使用的记忆功能是这个:
def memoize(func):
"""Store the results of the decorated function for fast lookup
"""
# Store results in a dict that maps arguments to results
cache = {}
def wrapper(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in cache:
cache[key] = func(*args, **kwargs)
return cache[key]
return wrapper
我的问题是:我可以设置消耗的缓存的大小,以便如果它已饱和并且必须在缓存中存储新输入,那么它将替换第一个条目-或者更好,最近最少使用。
先谢谢大家。
答案 0 :(得分:0)
如果它已经饱和并且必须将新输入存储在缓存中,那么它将替换第一个条目 - 或者更好,最近最少使用的条目。
考虑到您关心插入顺序,在决定删除哪些内容时,我建议使用 collections.OrderedDict 代替 dict
,即添加 import collections
并替换
cache = {}
使用
cache = collections.OrderedDict()
然后在插入后添加检查,如果大小超出限制就做:
cache.popitem(last=False)
放弃最旧的条目。