記憶體用量的程式剖析

撰寫高效的 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 筆 superheroes 資料集)

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

alt="魔術命令 mprun 的表格輸出,摘要記憶體使用剖析統計"

撰寫高效的 Python 程式碼

%mprun 輸出注意事項

小量的記憶體配置可能顯示為 0.0 MiB

(使用原始的 480 筆 superheroes 資料集)

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

alt="魔術命令 mprun 的表格輸出,摘要記憶體使用剖析統計,Increment 欄位所有列皆為 0.0 MiB"

撰寫高效的 Python 程式碼

%mprun 輸出注意事項

  • 透過查詢作業系統檢視記憶體
  • 各平台與不同執行結果可能不同
    • 仍可比較各程式碼行的記憶體消耗
撰寫高效的 Python 程式碼

一起來練習吧!

撰寫高效的 Python 程式碼

Preparing Video For Download...