高校倫理1436905 views
英語610681 views
高校国語786851 views
高校物理159041 views
小学理科718465 views
MathPython494531 views
数学講師2870390 views
雑学1473151 views
中学英語810312 views
中学理科1628645 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