memory_profiler模块
- 安装:通过
pip install memory_profiler
安装。
- 基本使用:
- 装饰器方式:在要检测内存使用的函数前添加
@profile
装饰器。例如:
@profile
def my_function():
data = [i**2 for i in range(1000000)]
return data
- 然后在命令行中使用
python -m memory_profiler your_script.py
运行脚本,它会输出函数执行过程中的内存使用情况。
tracemalloc模块
- 基本使用:
- 导入模块:
import tracemalloc
。
- 开始追踪:
tracemalloc.start()
。
- 在代码特定位置获取内存快照:
snapshot1 = tracemalloc.take_snapshot()
# 这里执行一些可能导致内存变化的代码
snapshot2 = tracemalloc.take_snapshot()
top_stats = snapshot2.compare_to(snapshot1, 'lineno')
for stat in top_stats[:10]:
print(stat)
- 停止追踪:
tracemalloc.stop()
。它可以帮助定位代码中哪些行导致了内存的增长。
objgraph模块
- 安装:通过
pip install objgraph
安装。
- 基本使用:
- 查找特定类型对象数量:例如
objgraph.count('list')
可统计当前存活的列表对象数量。
- 查找可能导致内存泄漏的对象引用链:
objgraph.show_growth()
可以显示哪些类型的对象数量增长最快,objgraph.show_backrefs([obj])
能显示对象obj
的反向引用链,有助于找到对象无法被垃圾回收的原因。