小学理科718021 views
中学社会667518 views
LaTeX958597 views
いろは2995081 views
世界の国561710 views
高校国語786382 views
中学理科1627838 views
Computer366119 views
高校化学2916128 views
高校倫理1435514 views

Python でプログラムのメモリ消費量をチェックする

tracemalloc ライブラリの get_traced_memory は Python プログラムのメモリ消費量を計測します。

import tracemalloc

tracemalloc.start()

nums = range(100000)

items = []

for num in nums:
	items.append(num * 5)

current, peak = tracemalloc.get_traced_memory()

print(f"現在の使用メモリ: {current / 1024 / 1024:.2f} MB")
print(f"ピークメモリ使用量: {peak / 1024 / 1024:.2f} MB")

tracemalloc.stop()

# 現在の使用メモリ: 3.81 MB
# ピークメモリ使用量: 3.81 MB