Python - 记录内存使用情况

Python - Log memory usage

在 python 3 中有没有办法记录内存 (ram) 使用情况,而某些程序正在 运行ning?

一些背景信息。我 运行 使用 slurm 在 hpc 集群上进行模拟,我必须在提交作业之前保留一些内存。我知道我的工作需要大量内存,但我不确定需要多少。所以我想知道是否有一个简单的解决方案可以随着时间的推移记录内存。

您可以使用 subprocess 模块。这是 bash 命令 free

的示例输出
$ free -m
             total       used       free     shared    buffers     cached
Mem:          7979       7678        300          0        109       4628
-/+ buffers/cache:       2941       5038
Swap:         2046        360       1686

Python 程序 -

import subprocess
result = subprocess.check_output(['bash','-c', 'free -m'])
free_memory = result.split('\n')[1].split()[3]
# print free_memory
# 300

如果您想检查某个进程的内存使用情况或定期记录它,那么您可以根据您的用例使用 pmap 或其他一些实用程序,然后解析输出。

您可以使用 memory_profiler 包来做到这一点。只需向函数添加装饰器 @profile,您将获得如下输出:

Line #    Mem usage  Increment   Line Contents
==============================================
 3                           @profile
 4      5.97 MB    0.00 MB   def my_func():
 5     13.61 MB    7.64 MB       a = [1] * (10 ** 6)
 6    166.20 MB  152.59 MB       b = [2] * (2 * 10 ** 7)
 7     13.61 MB -152.59 MB       del b
 8     13.61 MB    0.00 MB       return a

否则,最简单的方法是事后使用 sacct -l -j <JobId> 命令询问 Slurm(查找 MaxRSS 列),以便您可以适应进一步的工作。

此外,您可以在 运行 程序的同时使用 top 命令来了解其内存消耗情况。查找 RES 列。