内存使用的代码剖析

高效编写 Python 代码

Logan Thomas

Scientific Software Technical Trainer, Enthought

快捷粗略方法

import sys
nums_list = [*range(1000)]
sys.getsizeof(nums_list)
9112
import numpy as np

nums_np = np.array(range(1000))
sys.getsizeof(nums_np)
8096
高效编写 Python 代码

代码剖析:内存

  • 提供内存消耗的详细统计
  • 按行分析
  • 使用的包:memory_profiler
pip install memory_profiler
  • 使用 memory_profiler
%load_ext memory_profiler

%mprun -f convert_units convert_units(heroes, hts, wts)
高效编写 Python 代码

代码剖析:内存

  • 使用 memory_profiler 时需先导入函数
    • hero_funcs.py

 

from hero_funcs import convert_units
%load_ext memory_profiler

%mprun -f convert_units convert_units(heroes, hts, wts)
高效编写 Python 代码

%mprun 输出

%mprun -f convert_units convert_units(heroes, hts, wts)

alt="魔法命令 mprun 的表格输出,汇总内存剖析统计"

高效编写 Python 代码

%mprun 输出

%mprun -f convert_units convert_units(heroes, hts, wts)

alt="魔法命令 mprun 的表格输出,汇总内存剖析统计,并高亮 Line # 列"

高效编写 Python 代码

%mprun 输出

%mprun -f convert_units convert_units(heroes, hts, wts)

alt="魔法命令 mprun 的表格输出,汇总内存剖析统计,并高亮 Mem usage 列"

高效编写 Python 代码

%mprun 输出

%mprun -f convert_units convert_units(heroes, hts, wts)

alt="魔法命令 mprun 的表格输出,汇总内存剖析统计,并高亮 Increment 列"

高效编写 Python 代码

%mprun 输出

%mprun -f convert_units convert_units(heroes, hts, wts)

alt="魔法命令 mprun 的表格输出,汇总内存剖析统计,并高亮 Line contents 列"

高效编写 Python 代码

%mprun 输出

%mprun -f convert_units convert_units(heroes, hts, wts)

alt="魔法命令 mprun 的表格输出,汇总内存剖析统计"

高效编写 Python 代码

%mprun 输出注意事项

%mprun -f convert_units convert_units(heroes, hts, wts)

alt="魔法命令 mprun 的表格输出,汇总内存剖析统计,并高亮输出中的 mebibytes (MiB)"

高效编写 Python 代码

%mprun 输出注意事项

本示例数据为 35,000 名英雄的随机样本。

(非原始 480 超级英雄数据集)

%mprun -f convert_units convert_units(heroes, hts, wts)

alt="魔法命令 mprun 的表格输出,汇总内存剖析统计"

高效编写 Python 代码

%mprun 输出注意事项

较小的内存分配可能显示为 0.0 MiB

(使用原始 480 超级英雄数据集)

%mprun -f convert_units convert_units(heroes, hts, wts)

alt="魔法命令 mprun 的表格输出,汇总内存剖析统计,Increment 列各行均为 0.0 MiB"

高效编写 Python 代码

%mprun 输出注意事项

  • 通过查询操作系统检查内存
  • 结果在不同平台与运行间可能不同
    • 仍可比较各代码行的内存消耗
高效编写 Python 代码

让我们来练习!

高效编写 Python 代码

Preparing Video For Download...