LoginSignup
48
43

More than 5 years have passed since last update.

pythonで使用メモリを確認する方法

Posted at

メモリの使用量を減らすために,部分部分のメモリの使用量を確認したくなることが多々あります.
pythonではmemory_profilerを使うことで,メモリの使用量を確認できます.
ここでは簡単な使用方法について説明します.
詳しくは参考文献のサイトをご覧ください.

memory_profiler のインストール

pip install memory_profiler

このサイトによると,psutilもインストールすると速度が速くなるらしいです.

memory_profiler の使用方法

各行でのメモリ使用量を確認したい場合

以下のようにして各行でのメモリ使用量が確認できます.

memory1.py
from memory_profiler import profile

@profile
def test1(index):
  a = range(index)

if __name__ == "__main__":
  test1(2**20)

このようにすると,test1の各行のメモリ使用量が確認できます.メモリリークの確認がしたい時などに有効でしょう.

python memory1.py
Filename: memory1.py

Line #    Mem usage    Increment   Line Contents
================================================
     3     30.5 MiB     30.5 MiB   @profile
     4                             def test1(index):
     5     63.1 MiB     32.6 MiB     a = range(index)

使用メモリ量をプログラム中で使用したい場合

以下のようにして関数実行時のメモリ使用量が確認できます.

memory2.py
from memory_profiler import memory_usage

def test1(index):
  a = range(index)

if __name__ == "__main__":
  memory_out = memory_usage((test1, (2**20,)))
  print(memory_out)
python memory2.py
[63.0390625, 63.0390625, 63.0390625, 63.0390625, 63.0390625, 63.0390625, 63.0390625, 63.0390625, 63.0390625, 63.0390625]

memory_usageの使い方は,
memory_usage(proc=-1, interval=.1, timeout=None)
- proc: メモリを確認する関数等と引数をtupleにしたもの (↑での(test1, (2**20,)))
- interval: メモリを確認する時間幅
- timeout: いつまでメモリを確認するか Noneだと関数等が終わるまで

その他

mprofを使うと,matplotlibを使用して結果をプロットしてくれたりするらしい.
詳しくはここのサイトを確認してください

参考文献

http://www.sakito.com/2012/09/python-memoryprofiler.html
https://pypi.org/project/memory-profiler/
https://code.activestate.com/pypm/memory-profiler/
https://githubja.com/pythonprofilers/memory_profiler

48
43
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
48
43