我正在使用 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(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.
关于python - 字典大小和内存消耗之间的平衡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23072231/