在 Python 中使用 memory_profiler
可以监控代码的内存使用情况。以下是详细的使用方法:
1. 安装 memory_profiler
pip install memory_profiler
2. 基本用法
方法 1:装饰器模式(逐行分析)
在需要分析的函数上添加 @profile
装饰器,然后运行代码。
from memory_profiler import profile
@profile
def my_func():
a = [1] * 1000000 # 分配一个大列表
b = [2] * 2000000
del b # 删除 b 释放内存
return a
if __name__ == "__main__":
my_func()
运行命令
python -m memory_profiler your_script.py
输出示例
Line # Mem usage Increment Occurrences Line Contents
=============================================================
1 38.1 MiB 38.1 MiB 1 @profile
2 def my_func():
3 45.8 MiB 7.7 MiB 1 a = [1] * 1000000
4 61.5 MiB 15.7 MiB 1 b = [2] * 2000000
5 45.8 MiB -15.7 MiB 1 del b
6 45.8 MiB 0.0 MiB 1 return a
方法 2:代码中直接测量
如果不方便用装饰器,可以手动调用 memory_usage
。
from memory_profiler import memory_usage
def my_func():
a = [1] * 1000000
b = [2] * 2000000
return a
mem_usage = memory_usage((my_func, ()))
print(f"内存峰值: {max(mem_usage)} MiB")
方法 3:Jupyter Notebook 中使用
在 Notebook 中直接加载 memory_profiler
扩展:
%load_ext memory_profiler
# 单行分析
%memit [x for x in range(1000000)]
# 函数逐行分析
%%memit
def test():
a = [1] * 1000000
return a
test()
3. 关键参数
precision
: 输出内存数值的精度(默认1
,即小数点后 1 位)。stream
: 重定向输出(如写入文件)。interval
: 采样间隔时间(默认0.1
秒)。
示例:
@profile(precision=4, stream=open("mem_log.txt", "w+"))
def my_func():
# ...
4. 可视化工具(可选)
结合 matplotlib
绘制内存变化曲线:
from memory_profiler import memory_usage
import matplotlib.pyplot as plt
mem = memory_usage((my_func, ()))
plt.plot(mem)
plt.ylabel("Memory (MiB)")
plt.show()
注意事项
- 性能开销:
memory_profiler
会显著减慢代码运行速度,仅用于调试。 - 仅限单线程:多线程/多进程场景需要额外处理(如单独分析子进程)。
- 与
timeit
对比:%timeit
测时间,%memit
测内存。
如果有更复杂的需求(如分析内存泄漏),可以结合 objgraph
或 tracemalloc
等工具。