python - 通过 Python 函数跟踪*最大*内存使用情况

标签 python memory profiling

我想知道在调用函数期间分配的最大 RAM 量是多少(在 Python 中)。还有其他关于跟踪 RAM 使用情况的问题:

Which Python memory profiler is recommended?

How do I profile memory usage in Python?

但这些似乎允许您在调用 heap() 方法(在 guppy 的情况下)时更多地跟踪内存使用情况。但是,我要跟踪的是我无法修改的外部库中的一个函数,它会增长到使用大量 RAM,但一旦函数执行完成就会释放它。有什么方法可以查出函数调用期间使用的 RAM 总量是多少?

最佳答案

可以使用 memory_profiler 来做到这一点. memory_usage 函数返回一个值列表,这些值表示一段时间内的内存使用情况(默认情况下超过 0.1 秒的 block )。如果您需要最大值,只需取该列表中的最大值即可。小例子:

from memory_profiler import memory_usage
from time import sleep

def f():
    # a function that with growing
    # memory consumption
    a = [0] * 1000
    sleep(.1)
    b = a * 100
    sleep(.1)
    c = b * 100
    return a

mem_usage = memory_usage(f)
print('Memory usage (in chunks of .1 seconds): %s' % mem_usage)
print('Maximum memory usage: %s' % max(mem_usage))

在我的情况下(memory_profiler 0.25)如果打印以下输出:

Memory usage (in chunks of .1 seconds): [45.65625, 45.734375, 46.41015625, 53.734375]
Maximum memory usage: 53.734375

关于python - 通过 Python 函数跟踪*最大*内存使用情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9850995/

相关文章:

python - 如何用pyparsing解析这串数据结构

c - 记录动态内存分配使用情况

c - 结构中的字节顺序

python - 在Python中测量多线程代码的处理时间

python - PYLINT - 大量 "missing final newline"消息

python - Pip 错误,OSError Errno 22 参数无效

python - 如何让 Django 使用电子邮件而不是用户名注册用户

Perl Image::Magick 获取内存中的内容

linux - Systemtap 对性能的影响

java - 在 Java VisualVM 中看不到我自己的应用程序方法