美文网首页
Python对象通过引用计数排查脚本层内存泄漏

Python对象通过引用计数排查脚本层内存泄漏

作者: 水月心刀 | 来源:发表于2019-04-07 18:18 被阅读0次

    1. 获取目标对象的引用计数:

    import sys
    refcnt = sys.getrefcount(a)
    

    返回该对象目前的引用计数, 注意调用此函数时引用计数会+1

    sys.getrefcount(object):
    Return the reference count of the object. The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to getrefcount().

    2. 获取所有持有该对象的对象:

    import gc
    holderList = gc.get_referrers(obj)
    

    返回结果为List, 每个元素都是持有obj的独立对象(表现为dict)

    get_referrers(*objs):
    Return the list of objects that directly refer to any of objs. This function will only locate those containers which support garbage collection; extension types which do refer to other objects but do not support garbage collection will not be found.
    Note that objects which have already been dereferenced, but which live in cycles and have not yet been collected by the garbage collector can be listed among the resulting referrers. To get only currently live objects, call collect() before calling get_referrers().

    3. 获取该对象持有的所有对象:

    import gc
    beHolderList = gc.get_referents(obj)
    

    gc.get_referents(*objs)
    Return a list of objects directly referred to by any of the arguments. The referents returned are those objects visited by the arguments’ C-level tp_traverse methods (if any), and may not be all objects actually directly reachable. tp_traverse methods are supported only by objects that support garbage collection, and are only required to visit objects that may be involved in a cycle. So, for example, if an integer is directly reachable from an argument, that integer object may or may not appear in the result list.

    相关文章

      网友评论

          本文标题:Python对象通过引用计数排查脚本层内存泄漏

          本文链接:https://www.haomeiwen.com/subject/nvosiqtx.html