【问题标题】:python check memory usage and stop caching if memory usage is too highpython 检查内存使用情况并在内存使用量过高时停止缓存
【发布时间】:2021-09-13 15:49:39
【问题描述】:

我希望在内存中缓存一些 DataFrame 以加快我的程序速度(calculate_df 很慢)。我的代码是这样的

class Foo:
    cache = {}

    @classmethod
    def get_df(cls, bar):
        if bar not in cache:
            cls.cache[bar] = cls.calculate_df(bar)
        return cls.cache[bar]

    @classmethod
    def calculate_df(cls, bar):
        ......
        return df

几乎所有时间,bar 的可能值乘以 df 的大小都适合内存。但是,我需要为我有太多不同的bars 和大df 的情况做计划,这会使我的cache 导致内存问题。我希望在运行cache[bar] = calculate_df(bar)之前先检查内存使用情况。

进行此类内存检查的正确/最佳方法是什么?

【问题讨论】:

  • 告诉您可以使用多少缓存空间的规则是什么?发生了哪些“内存问题”,为什么会出现问题?
  • 我还没有遇到“内存问题”,但我只是在考虑糟糕的情况。基本上如果内存使用率太高,我想停止将它们添加到cls.cache 并直接返回。我不知道告诉我可以使用多少缓存空间的规则是什么,我想这也是我的问题的一部分。看来我可以使用psutil.virtual_memory().available

标签: python pandas memory-management


【解决方案1】:

您可能需要考虑使用装饰器functools.lru_cache(),而不是在 Python 中手动操作此类内存级别,您可以在其中将可以在任何给定时间点存储的项目数限制为maxsize。一旦到达maxsize,它将驱逐旧项目。

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

装饰器用一个可保存到maxsize最近调用的记忆可调用函数来包装函数

使用示例

from functools import lru_cache

class MyClass:
    @lru_cache(maxsize=3)
    def duplicate(self, num):
        print("called for", num)
        return num * 2

obj = MyClass()
for num in [12, 7, 12, 12, 7, 5, 15, 5, 7, 12]:
    print(num, "=", obj.duplicate(num))

输出

called for 12
12 = 24
called for 7
7 = 14
12 = 24
12 = 24
7 = 14
called for 5
5 = 10
called for 15
15 = 30
5 = 10
7 = 14
called for 12
12 = 24

【讨论】:

  • 感谢您的建议。我的功能其实更复杂: 1. 我想自己清理缓存,因为我知道在什么情况下它们不再使用。我的缓存清理策略可以将大小减少数百倍 2. lru_cache 似乎只考虑输入的最大大小。就我而言,这只是一个很小的因素。更重要的因素是计算出的 DataFrame 的大小。因此 lru_cache 对我来说似乎不是一个好的解决方案。你怎么看?
  • 看来我可以破解 lru_cache 以使用 use_memory_up_to: stackoverflow.com/questions/23477284/… 但这与我自己检查缓存空间几乎相同
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-11
  • 1970-01-01
  • 2012-01-03
  • 1970-01-01
相关资源
最近更新 更多