2017/02/15

pythonのラインプロファイラ

各行毎のメモリ消費量を調べるmemory_profilerと実行時間を調べるline_profilerの使い方メモ.

まず,memory_profiler の使い方

pipでインストール.


sudo pip install memory_profiler


調べたい関数の前に
@profile
を付ける.

例えば以下のようなtest.pyを作る.

@profile
def main():
    l = [[1,2,3,4]] * 100000
    d = [{'first': 1, 'second': 2, 'third': 3, 'fourth': 4}] * 100000

if __name__ == '__main__':
    main()
    print("Hello world!!")


あとは

python -m memory_profiler test.py

のように -m オプション付きで実行するだけで,以下のような出力が得られる.

Hello world!!
Filename: test.py

Line #    Mem usage    Increment   Line Contents
================================================
    17   28.488 MiB    0.000 MiB   @profile
    18                             def main():
    19   29.270 MiB    0.781 MiB       l = [[1,2,3,4]] * 100000

    20   30.039 MiB    0.770 MiB       d = [{'first': 1, 'second': 2, 'third': 3, 'fourth': 4}] * 100000

Incrementの欄を見れば
各行のメモリ消費量が確認できる.



line_profilerの方もpipでインストール.

sudo pip install line_profiler

上記のtest.pyを

kernprof -l test.py


のようにkernprofで実行すると


test.py.lprof

というファイルができている
これをさらに

python -m line_profiler test.py.lprof

のように実行すると,以下のような出力が得られる


Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
    17                                           @profile
    18                                           def main():
    19         1          418    418.0     56.0      l = [[1,2,3,4]] * 100000
    20         1          329    329.0     44.0      d = [{'first': 1, 'second': 2, 'third': 3, 'fourth': 4}] * 100000




0 件のコメント:

コメントを投稿