小学社会309222 views
小学算数1197982 views
いろは2999528 views
英語610681 views
高校化学2918182 views
教育149228 views
中学社会667713 views
中学英語810312 views
数学講師2870390 views
MathPython494531 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