MST

星途 面试题库

面试题:Python中内存泄漏检测常用模块及基本使用

请简要介绍Python中用于检测内存泄漏的常用模块,并说明其基本使用方法。
20.4万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试

memory_profiler模块

  1. 安装:通过pip install memory_profiler安装。
  2. 基本使用
    • 装饰器方式:在要检测内存使用的函数前添加@profile装饰器。例如:
@profile
def my_function():
    data = [i**2 for i in range(1000000)]
    return data
  • 然后在命令行中使用python -m memory_profiler your_script.py运行脚本,它会输出函数执行过程中的内存使用情况。

tracemalloc模块

  1. 基本使用
    • 导入模块: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模块

  1. 安装:通过pip install objgraph安装。
  2. 基本使用
    • 查找特定类型对象数量:例如objgraph.count('list')可统计当前存活的列表对象数量。
    • 查找可能导致内存泄漏的对象引用链:objgraph.show_growth()可以显示哪些类型的对象数量增长最快,objgraph.show_backrefs([obj])能显示对象obj的反向引用链,有助于找到对象无法被垃圾回收的原因。