Python追蹤記憶體使用

最近同事用Python開發Server遇到記憶體的heap越用越大的問題

追蹤過程中偶然發現python一個可以追蹤當前記憶體使用的套件:Pympler

不只可以追蹤每段時間的記憶體差別

from pympler import tracker
tr = tracker.SummaryTracker()
v = "Hello"
tr.print_diff()

“”“
  types |   # objects |   total size

======= | =========== | ============
    str |           2 |     97     B
   list |           1 |     96     B
    int |           1 |     24     B
”“”

還有一個memory leak追蹤工具可以像JAVA的jmap工具一樣觀察現在記憶體都用到哪些物件去了
http://pythonhosted.org/Pympler/muppy.html#muppy

from pympler import muppy
from pympler import summary
all_objects = muppy.get_objects()
sum1 = summary.summarize(all_objects)
summary.print_(sum1)  

"""
                       types |   # objects |   total size
============================ | =========== | ============
                        dict |         641 |      1.01 MB
                         str |        8876 |    773.97 KB
                        list |        1789 |    366.43 KB
                        code |        2116 |    264.50 KB
                        type |         109 |     96.23 KB
          wrapper_descriptor |        1105 |     86.33 KB
  builtin_function_or_method |         794 |     55.83 KB
           method_descriptor |         618 |     43.45 KB
                         set |         134 |     36.36 KB
                     weakref |         401 |     34.46 KB
                       tuple |         402 |     29.59 KB
         <class 'abc.ABCMeta |          20 |     17.66 KB
           member_descriptor |         245 |     17.23 KB
         function (__init__) |         124 |     14.53 KB
           getset_descriptor |         197 |     13.85 KB
"""

還沒很深入的去玩,這邊先做個記錄

comments powered by Disqus