Python - Working around memory leaks

后端 未结 4 1860
别那么骄傲
别那么骄傲 2020-11-30 19:41

I have a Python program that runs a series of experiments, with no data intended to be stored from one test to another. My code contains a memory leak which I am completely

4条回答
  •  情书的邮戳
    2020-11-30 20:17

    You can use something like this to help track down memory leaks

    >>> from collections import defaultdict
    >>> from gc import get_objects
    >>> before = defaultdict(int)
    >>> after = defaultdict(int)
    >>> for i in get_objects():
    ...     before[type(i)] += 1 
    ... 
    

    now suppose the tests leaks some memory

    >>> leaked_things = [[x] for x in range(10)]
    >>> for i in get_objects():
    ...     after[type(i)] += 1
    ... 
    >>> print [(k, after[k] - before[k]) for k in after if after[k] - before[k]]
    [(, 11)]
    

    11 because we have leaked one list containing 10 more lists

提交回复
热议问题