一些情况下,预期之外的内存占用过多时,需要分析代码哪个位置消耗内存,从而针对性的优化代码,本文介绍一些方便的工具可用于内存分析。
1. memory_profiler
memory_profiler 可逐行分析内存占用情况,提供最直接明了的信息。
调用方式
from memory_profiler import profile
@profile(precision=4, stream=open('mem.log','w+')) # 也可不使用参数
def func(x):
# process
stream:设置输出到指定文件,不指定则打印到标准输出;
结果说明
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
Line :代码在脚本中的行号;
Mem usage:该行执行后的内存占用;
Increment:该行执行产生的内存增长;
Line Contents:具体代码;
其他用法
mprof 可输出程序随时间变化的内存使用变化,并能可视化。此时并非按行计算内存消耗,而是程序整体内存使用情况。
函数前使用profile 装饰器后,mprof可输出对应函数在相应运行时间段的内存使用。
mprof run <script> # 输出文件到当前目录
mprof plot #可视化
# 汇总所有子进程和父进程的内存使用
mprof run --include-children <script>
# 独立于主进程,追踪每个子进程的内存使用
mprof run -