python - 字典大小和内存消耗之间的平衡

标签 python algorithm memory data-structures dictionary

我正在使用 memoized decorator缓存重复调用。由于对一些中等大小的测试用例进行内存,我发现执行速度提高了大约 4 倍。

对于较大的测试用例,将输入映射到输出的内存字典会占用大量内存,以至于我收到 "java.lang.OutOfMemoryError: Java heap space" 错误(我正在使用 Jython)。

我可以通过使用 memoized_cache[hash(key)] = value 而不是 memoized_cache[key]: value 来节省一些内存,假设 hash(key )key 的字节数少。正如@gnibbler 所指出的,如果存在哈希冲突,这将导致问题。

我可以介绍的其他内存节省是将字典的大小限制为固定数量的项目。这样一个SizedDict recipe已经存在,但我想截断访问次数最少的元素。

这是我写的:

from collections import Counter

class FrequencySizedDict(dict):
    def __init__(self, size=1000):
        dict.__init__(self)
        self._maxsize = size
        self._counter = Counter()
    def __getitem__(self, key):
        self._counter[key] += 1
        return dict.__getitem__(self, key)
    def resize(self, size):
        keys = list(self._counter.most_common(size))
        items = [(key, dict.__getitem__(self, key)) for key in keys]
        self.clear()
        dict.update(self, items)
    def __setitem__(self, key, value):
        if len(self._queue) >= self._maxsize:
            self.resize(self._maxsize/2)
        self._counter[key] += 1
        dict.__setitem__(self, key, value)

是否有更好的数据方式以更少的内存或时间开销来实现这一点? resize 非常昂贵:O(n log n)

最佳答案

使用functools.lru_cache

@functools.lru_cache(maxsize=128, typed=False)

Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls. It can save time when an expensive or I/O bound function is periodically called with the same arguments.

pylru如答案 memoization library for python 2.7 中所述

关于python - 字典大小和内存消耗之间的平衡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23072231/

相关文章:

windows - WriteProcessMemory ERROR_PARTIAL_COPY 299

python - 让 python 程序等到 Twisted deferred 返回一个值

python - 需要在 Python 中 reshape /转置 Dataframe

algorithm - 广度优先搜索生成的节点数是多少?

algorithm - 在流网络的所有最小切割中找到最少的边缘

java - Java中如何确定对象的大小

java - 如何将Java进程锁定到内存? (M锁)

使用类(wx.Python)时出现Python TypeError

python - 使用 BeautifulSoup 进行网络抓取表

algorithm - 简单范围搜索算法的伪代码