メモリリーク時に JVM の jmap や C/C++ の Valgrind で調査できるのと同様に、Python では objgraph が便利です。
sudo apt install graphviz
python -m pip install xdot
python -m pip install objgraph
sample.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
from objgraph import show_most_common_types
class MyBigFatObject(object):
pass
def Main():
obj = MyBigFatObject()
show_most_common_types(limit=999)
if __name__ == '__main__':
Main()
出力例
$ python sample.py | grep MyBigFatObject
MyBigFatObject 1
#!/usr/bin/python
# -*- coding: utf-8 -*-
from objgraph import count
class MyBigFatObject(object):
pass
def Main():
obj = MyBigFatObject()
print count('MyBigFatObject') #=> 1
if __name__ == '__main__':
Main()
最後に growth/show_growth
した時点からの、オブジェクトの増加数を表示できます。
sample.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
from objgraph import growth
from objgraph import show_growth
class MyBigFatObject(object):
pass
def Main():
growth()
growth()
obj = MyBigFatObject()
show_growth(limit=999)
if __name__ == '__main__':
Main()
出力例
$ python sample.py
frame 5 +1
MyBigFatObject 1 +1
sample.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
from objgraph import show_refs
class MyBigFatObject(object):
pass
def Main():
x = [1, {'mykey': 'myval'}]
for i in range(2):
x.append(MyBigFatObject())
show_refs([x], filename='sample-graph.png')
if __name__ == '__main__':
Main()
出力例