Python Objgraph

Table of Contents

1. Python Objgraph (内存泄露, memory leak)

import objgraph as og
import time

class Test(object):
    def __init__(self):
        pass

x = []
while True:
    import pdb; pdb.set_trace()
    for i in range(100):
        x.append(Test())
  1. og.show_growth 找到可疑的对象名称
  2. og.by_type 找到具体的对象
  3. og.find_backref_chain 打到对象对 gc root 的路径
  4. og.show_chain 打印出路径

除此之外, og 还有以下函数:

  • show_refs
  • show_backrefs
  • find_ref_chain
  • count
  • show_most_common_types
#>./test.py
-> for i in range(100):
(Pdb) og.show_growth()
function                       2104     +2104
wrapper_descriptor             1063     +1063
dict                           1009     +1009
builtin_function_or_method      822      +822
tuple                           799      +799
method_descriptor               727      +727
weakref                         716      +716
getset_descriptor               379      +379
member_descriptor               313      +313
type                            285      +285
(Pdb) og.show_growth()
(Pdb) c
> /tmp/emacs-playgroud-python/playground.py(13)<module>()
-> import pdb; pdb.set_trace()
(Pdb) og.show_growth()
Test      100      +100
(Pdb) c
> /tmp/emacs-playgroud-python/playground.py(14)<module>()
-> for i in range(100):
(Pdb) og.show_growth()
Test      200      +100
(Pdb) chain=og.find_backref_chain(og.by_type("Test")[0],og.is_proper_module)
(Pdb) og.show_chain(chain)

Author: [email protected]
Date: 2020-11-11 Wed 00:00
Last updated: 2020-11-16 Mon 20:28

知识共享许可协议