Python垃圾回收机制:gc模块

简介:

 在Python中,为了解决内存泄露问题,采用了对象引用计数,并基于引用计数实现自动垃圾回

    由于Python 有了自动垃圾回收功能,就造成了不少初学者误认为不必再受内存泄漏的骚扰了。但如果仔细查看一下Python文档对 __del__() 函数的描述,就知道这种好日子里也是有阴云的。下面摘抄一点文档内容如下:

Some common situations that may prevent the reference count of an object from going to zero include: circular references between objects (e.g., a doubly-linked list or a tree data structure with parent and child pointers); a reference to the object on the stack frame of a function that caught an exception (the traceback stored in sys.exc_traceback keeps the stack frame alive); or a reference to the object on the stack frame that raised an unhandled exception in interactive mode (the traceback stored in sys.last_traceback keeps the stack frame alive).

  可见, __del__() 函数的对象间的循环引用是导致内存泄漏的主凶。但没有__del__()函数的对象间的循环引用是可以被垃圾回收器回收掉的。

    如何知道一个对象是否内存泄露掉了呢?

    可以通过Python的扩展模块gc来查看不能回收掉的对象的详细信息。

 

例1:没有出现内存泄露的

复制代码
import gc
import sys

class CGcLeak(object):
    def __init__(self):
        self._text = '#' * 10

    def __del__(self):
        pass

def make_circle_ref():
    _gcleak = CGcLeak()
    print "_gcleak ref count0: %d" %(sys.getrefcount(_gcleak))
    del _gcleak
    try:
        print "_gcleak ref count1 :%d" %(sys.getrefcount(_gcleak))
    except UnboundLocalError:           # 本地变量xxx引用前没定义
        print "_gcleak is invalid!"
def test_gcleak():
    gc.enable()                         #设置垃圾回收器调试标志
    gc.set_debug(gc.DEBUG_COLLECTABLE | gc.DEBUG_UNCOLLECTABLE | gc.DEBUG_INSTANCES | gc.DEBUG_OBJECTS)

    print "begin leak test..."
    make_circle_ref()

    print "\nbegin collect..."
    _unreachable = gc.collect()
    print "unreachable object num:%d" %(_unreachable)
    print "garbage object num:%d" %(len(gc.garbage))   #gc.garbage是一个list对象,列表项是垃圾收集器发现的不可达(即垃圾对象)、但又不能释放(不可回收)的对象,通常gc.garbage中的对象是引用对象还中的对象。因Python不知用什么顺序来调用对象的__del__函数,导致对象始终存活在gc.garbage中,造成内存泄露 if __name__ == "__main__": test_gcleak()。如果知道一个安全次序,那么就可以打破引用焕,再执行del gc.garbage[:]从而清空垃圾对象列表
if __name__ == "__main__":
    test_gcleak()
复制代码

 结果

复制代码
begin leak test...
_gcleak ref count0: 2         #对象_gcleak的引用计数为2
_gcleak is invalid!           #因为执行了del函数,_gcleak变为了不可达的对象

begin collect...              #开始垃圾回收
unreachable object num:0      #本次垃圾回收发现的不可达的对象个数为0
garbage object num:0          #整个解释器中垃圾对象的个数为0
复制代码

    结论是对象_gcleak的引用计数是正确的,也没发生内存泄漏。

 

例2:对自己的循环引用造成内存泄露

复制代码
import gc
import sys

class CGcLeak(object):
    def __init__(self):
        self._text = '#' * 10

    def __del__(self):
        pass

def make_circle_ref():
    _gcleak = CGcLeak()
    _gcleak._self = _gcleak     #自己循环引用自己
    print "_gcleak ref count0: %d" %(sys.getrefcount(_gcleak))
    del _gcleak
    try:
        print "_gcleak ref count1 :%d" %(sys.getrefcount(_gcleak))
    except UnboundLocalError:
        print "_gcleak is invalid!"

def test_gcleak():
    gc.enable()
    gc.set_debug(gc.DEBUG_COLLECTABLE | gc.DEBUG_UNCOLLECTABLE | gc.DEBUG_INSTANCES | gc.DEBUG_OBJECTS)

    print "begin leak test..."
    make_circle_ref()

    print "\nbegin collect..."
    _unreachable = gc.collect()
    print "unreachable object num:%d" %(_unreachable)
    print "garbage object num:%d" %(len(gc.garbage))

if __name__ == "__main__":
    test_gcleak()
复制代码

结果

复制代码
begin leak test...
gc: uncollectable <CGcLeak 00000000026366A0>
_gcleak ref count0: 3
_gcleak is invalid!
gc: uncollectable <dict 0000000002667BD8>

begin collect...
unreachable object num:2       #本次回收不可达的对象个数为2
garbage object num:1           #整个解释器中垃圾个数为1
复制代码

 

例3:多个对象间的循环引用造成内存泄露 

复制代码
import gc
import sys

class CGcLeakA(object):
    def __init__(self):
        self._text = '$' * 10

    def __del__(self):
        pass

class CGcLeakB(object):
    def __init__(self):
        self._text = '$' * 10

    def __del__(self):
        pass

def make_circle_ref():
    _a = CGcLeakA()
    _b = CGcLeakB()
    _a.s = _b
    _b.d = _a
    print "ref count0:a=%d b=%d" %(sys.getrefcount(_a), sys.getrefcount(_b))
    del _a
    del _b
    try:
        print "ref count1:a%d" %(sys.getrefcount(_a))
    except UnboundLocalError:
        print "_a is invalid!"

def test_gcleak():
    gc.enable()
    gc.set_debug(gc.DEBUG_COLLECTABLE | gc.DEBUG_UNCOLLECTABLE | gc.DEBUG_INSTANCES | gc.DEBUG_OBJECTS)

    print "begin leak test..."
    make_circle_ref()

    print "\nbegin collect..."
    _unreachable = gc.collect()
    print "unreachable object num:%d" %(_unreachable)
    print "garbage object num:%d" %(len(gc.garbage))

if __name__ == "__main__":
    test_gcleak()
复制代码

结果

1
2
3
4
5
6
7
8
9
10
11
begin leak test...
ref count 0: a= 3  b= 3
_a is invalid!
 
begin collect...
unreachable object num: 4
garbage object num: 2
gc: uncollectable <CGcLeakA  00000000022766 D 8 >
gc: uncollectable <CGcLeakB  0000000002276710 >
gc: uncollectable <dict  00000000022 A 7 E 18 >
gc: uncollectable <dict  00000000022 DF 3 C 8 >

 

结论

    Python 的 gc 有比较强的功能,比如设置 gc.set_debug(gc.DEBUG_LEAK) 就可以进行循环引用导致的内存泄露的检查。如果在开发时进行内存泄露检查;在发布时能够确保不会内存泄露,那么就可以延长 Python 的垃圾回收时间间隔、甚至主动关闭垃圾回收机制,从而提高运行效率。

 

有待于深入研究的知识:监控Python中的引用计数

参考:Python的内存泄漏及gc模块的使用分析

 





本文转自jihite博客园博客,原文链接:http://www.cnblogs.com/kaituorensheng/p/4449457.html,如需转载请自行联系原作者

相关文章
|
22天前
|
存储 开发者 Python
Python中的collections模块与UserDict:用户自定义字典详解
【4月更文挑战第2天】在Python中,`collections.UserDict`是用于创建自定义字典行为的基类,它提供了一个可扩展的接口。通过继承`UserDict`,可以轻松添加或修改字典功能,如在`__init__`和`__setitem__`等方法中插入自定义逻辑。使用`UserDict`有助于保持代码可读性和可维护性,而不是直接继承内置的`dict`。例如,可以创建一个`LoggingDict`类,在设置键值对时记录操作。这样,开发者可以根据具体需求定制字典行为,同时保持对字典内部管理的抽象。
|
1天前
|
开发者 Python
Python的os模块详解
Python的os模块详解
9 0
|
4天前
|
数据挖掘 API 数据安全/隐私保护
python请求模块requests如何添加代理ip
python请求模块requests如何添加代理ip
|
6天前
|
测试技术 Python
Python 有趣的模块之pynupt——通过pynput控制鼠标和键盘
Python 有趣的模块之pynupt——通过pynput控制鼠标和键盘
|
6天前
|
Serverless 开发者 Python
《Python 简易速速上手小册》第3章:Python 的函数和模块(2024 最新版)
《Python 简易速速上手小册》第3章:Python 的函数和模块(2024 最新版)
38 1
|
8天前
|
Python
python学习-函数模块,数据结构,字符串和列表(下)
python学习-函数模块,数据结构,字符串和列表
49 0
|
9天前
|
Python
python学习14-模块与包
python学习14-模块与包
|
11天前
|
SQL 关系型数据库 数据库
Python中SQLite数据库操作详解:利用sqlite3模块
【4月更文挑战第13天】在Python编程中,SQLite数据库是一个轻量级的关系型数据库管理系统,它包含在一个单一的文件内,不需要一个单独的服务器进程或操作系统级别的配置。由于其简单易用和高效性,SQLite经常作为应用程序的本地数据库解决方案。Python的内置sqlite3模块提供了与SQLite数据库交互的接口,使得在Python中操作SQLite数据库变得非常容易。
|
16天前
|
索引 Python
「Python系列」Python operator模块、math模块
Python的`operator`模块提供了一系列内置的操作符函数,这些函数对应于Python语言中的内建操作符。使用`operator`模块可以使代码更加清晰和易读,同时也能提高性能,因为它通常比使用Python内建操作符更快。
27 0
|
20天前
|
数据采集 网络协议 API
python中其他网络相关的模块和库简介
【4月更文挑战第4天】Python网络编程有多个流行模块和库,如requests提供简洁的HTTP客户端API,支持多种HTTP方法和自动处理复杂功能;Scrapy是高效的网络爬虫框架,适用于数据挖掘和自动化测试;aiohttp基于asyncio的异步HTTP库,用于构建高性能Web应用;Twisted是事件驱动的网络引擎,支持多种协议和异步编程;Flask和Django分别是轻量级和全栈Web框架,方便构建不同规模的Web应用。这些工具使网络编程更简单和高效。