使用 %mprun:Hero BMI 2.0
來看看用不同的計算方式是否能節省記憶體。還記得嗎?每位英雄的身高與體重都存放在 numpy 陣列中。這表示你可以利用 NumPy 方便的陣列索引能力與廣播(broadcasting)來進行計算。已經建立一個名為 calc_bmi_arrays 的函式,並儲存在 bmi_arrays.py 檔案中。為了方便,內容如下:
def calc_bmi_arrays(sample_indices, hts, wts):
# Gather sample heights and weights as arrays
s_hts = hts[sample_indices]
s_wts = wts[sample_indices]
# Convert heights from cm to m and square with broadcasting
s_hts_m_sqr = (s_hts / 100) ** 2
# Calculate BMIs as an array using broadcasting
bmis = s_wts / s_hts_m_sqr
return bmis
請注意,這個函式使用「陣列」完成所有必要的計算。
來看看這種更新後的陣列做法是否能降低記憶體占用:
- 在你的 IPython 工作階段中載入
memory_profiler套件。 - 從
bmi_arrays匯入calc_bmi_arrays。 - 完成以上步驟後,使用
%mprun來剖析套用在你的超級英雄資料上的calc_bmi_arrays()函式。sample_indices陣列、hts陣列與wts陣列已載入到你的工作階段中。
完成撰寫後,請回答下列問題:
「在 calc_bmi_array() 函式中,進行陣列索引與廣播的這幾行程式碼共消耗多少記憶體?(也就是這四行程式碼的 Increment 欄位加總是多少?)」
本練習屬於課程
