LoginSignup
66
67

More than 5 years have passed since last update.

Pythonでメモリリーク調べる

Last updated at Posted at 2015-05-13

簡単なメモリリーク調査の作業手順渡して依頼する必要会ったのでこっちにもまとめた

guppyとかheapyとか使ってたけど、tracemallocが3.4系で標準になっていて、snapshot間の差分なんかも取れるので今後はこいつ一択で良さそう

3.3系まではpytracemallocモジュールをインストールして使う

使い方

メモリ使用量のリスト見る

import tracemalloc

tracemalloc.start()

# ... run your application ...

snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('lineno')

mallocでメモリを確保した行毎に確保ブロック数とサイズが出る

差分見る

大体これで問題の把握は事足りる

import tracemalloc
tracemalloc.start()
# ... start your application ...

snapshot1 = tracemalloc.take_snapshot()
# ... call the function leaking memory ...
snapshot2 = tracemalloc.take_snapshot()

top_stats = snapshot2.compare_to(snapshot1, 'lineno')

print("[ Top 10 differences ]")
for stat in top_stats[:10]:
    print(stat)

mallocが走った行毎のブロック数とサイズの差分が出るので、関数実行しても開放されないメモリとかが差分として出てくる

66
67
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
66
67