【问题标题】:Memoization: set the size of the consumed cacheMemoization:设置消耗缓存的大小
【发布时间】:2021-05-25 21:53:34
【问题描述】:

我正在使用 memoization 来加快复杂函数 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

我的问题是:我可以设置消耗缓存的大小,这样如果它已经饱和并且必须将新输入存储在缓存中,那么它将替换第一个条目 -或者更好,最近最少使用。

先谢谢大家了。

【问题讨论】:

    标签: python caching memoization


    【解决方案1】:

    如果它已饱和并且必须将新输入存储在缓存中,那么它将替换第一个条目 - 或者更好的是,最近最少使用的条目。

    考虑到您关心插入顺序,在决定删除什么时,我建议使用collections.OrderedDict 代替dict,即添加import collections 并替换

    cache = {}
    

    使用

    cache = collections.OrderedDict()
    

    然后在插入后添加检查,如果大小超出限制就这样做:

    cache.popitem(last=False)
    

    放弃最旧的条目。

    【讨论】:

    • 这可能对我有用.. 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2017-10-07
    • 1970-01-01
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-14
    • 2015-04-04
    相关资源
    最近更新 更多