0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[スニペット]Pythonでメモリの使用状況を出力する

Last updated at Posted at 2025-05-02

psutil を使う(クロスプラットフォーム)
psutil はプロセス情報を簡単に取得できる外部ライブラリです。
以下のように現在プロセスの RSS(Resident Set Size=常駐メモリ量)を取得して print()/logging に流せます。

import os
import psutil
import logging

# ロガー設定
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def get_memory_mb():
    process = psutil.Process(os.getpid())
    # rss はバイト単位なので MB に変換
    return process.memory_info().rss / (1024 * 1024)

if __name__ == "__main__":
    logger.info(f"Start: {get_memory_mb():.2f} MB")
    # — ここでメモリを消費する処理 —
    data = [i for i in range(10**7)]
    logger.info(f"After allocation: {get_memory_mb():.2f} MB")
    del data
    logger.info(f"After free: {get_memory_mb():.2f} MB")

tracemalloc を使う(Python標準)
Python3.4+ 標準の tracemalloc で、スナップショット単位にメモリ使用量を確認できます。
ポイント
コード内のどの行でメモリが増えたか解析可能
長時間追跡するとオーバーヘッドがあるので必要な範囲で使用

import tracemalloc

def your_function():
    data = [i for i in range(10**7)]
    return data

if __name__ == "__main__":
    tracemalloc.start()

    snapshot1 = tracemalloc.take_snapshot()
    your_function()
    snapshot2 = tracemalloc.take_snapshot()

    stats = snapshot2.compare_to(snapshot1, 'lineno')
    for stat in stats[:5]:
        print(stat)
    
    current, peak = tracemalloc.get_traced_memory()
    print(f"Current: {current / 1024**2:.2f} MB; Peak: {peak / 1024**2:.2f} MB")

    tracemalloc.stop()
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?