在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:{}".format(sys.getrefcount(_gcleak)))
del _gcleak try:
print("_gcleak ref count:{}".format(sys.getrefcount(_gcleak)))
except UnboundLocalError:
print("_gcleak is invalid!") def test_gcleak():
gc.enable() print("begin leak test...")
make_circle_ref() print
"\nbegin collect..."
_unreachable = gc.collect()
print("unreachable object num:{}".format(_unreachable))
print("garbage object num:{}".format(len(gc.garbage))) if __name__ == "__main__":
test_gcleak()

结果

C:\Python35\python.exe C:/wcf/django/ftest/ftest.py
begin leak test...
_gcleak ref count0:2
_gcleak is invalid!
unreachable object num:0
garbage object num:0 Process finished with exit code 0

例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:{}".format(sys.getrefcount(_gcleak)))
del _gcleak try:
print("_gcleak ref count:{}".format(sys.getrefcount(_gcleak)))
except UnboundLocalError:
print("_gcleak is invalid!") def test_gcleak():
gc.enable() print("begin leak test...")
make_circle_ref() print
"\nbegin collect..."
_unreachable = gc.collect()
print("unreachable object num:{}".format(_unreachable))
print("garbage object num:{}".format(len(gc.garbage))) if __name__ == "__main__":
test_gcleak()

结果是:

C:\Python35\python.exe C:/wcf/django/ftest/ftest.py
begin leak test...
_gcleak ref count0:3
_gcleak is invalid!
unreachable object num:2
garbage object num:0 Process finished with exit code 0

例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.s=_a print("ref count0:_a is {},_b is {}".format(sys.getrefcount(_a),sys.getrefcount(_a)))
del _a
del _b try:
print("ref count:_a is {}".format(sys.getrefcount(_a)))
except UnboundLocalError:
print("_a is invalid!") def test_gcleak():
gc.enable() print("begin leak test...")
make_circle_ref() print
"\nbegin collect..."
_unreachable = gc.collect()
print("unreachable object num:{}".format(_unreachable))
print("garbage object num:{}".format(len(gc.garbage))) if __name__ == "__main__":
test_gcleak()

运行结果:

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.s=_a print("ref count0:_a is {},_b is {}".format(sys.getrefcount(_a),sys.getrefcount(_a)))
del _a
del _b try:
print("ref count:_a is {}".format(sys.getrefcount(_a)))
except UnboundLocalError:
print("_a is invalid!") def test_gcleak():
gc.enable() print("begin leak test...")
make_circle_ref() print
"\nbegin collect..."
_unreachable = gc.collect()
print("unreachable object num:{}".format(_unreachable))
print("garbage object num:{}".format(len(gc.garbage))) if __name__ == "__main__":
test_gcleak()

转自:

http://www.cnblogs.com/kaituorensheng/p/4449457.html

Python垃圾回收机制:gc模块(zz)的更多相关文章

  1. Python垃圾回收机制:gc模块

    在Python中,为了解决内存泄露问题,采用了对象引用计数,并基于引用计数实现自动垃圾回收. 由于Python 有了自动垃圾回收功能,就造成了不少初学者误认为不必再受内存泄漏的骚扰了.但如果仔细查看一 ...

  2. 浅析Python垃圾回收机制!

    Python垃圾回收机制 目录 Python垃圾回收机制 1. 内存泄露 2. Python什么时候启动垃圾回收机制? 2.1 计数引用 2.2 循环引用 问题:引用计数是0是启动垃圾回收的充要条件吗 ...

  3. 简述Python垃圾回收机制和常量池的验证

    目录 通过代码验证python解释器内部使用了常量池 Python的引入 变量的引入 为什么要有变量 定义变量 常量引入 常量池引入 Python解释器 Python变量存储机制 Python垃圾回收 ...

  4. 垃圾回收机制GC

    垃圾回收机制GC 我们已经知道,name = 'leethon'这一赋值变量的操作,是将变量与数据值相绑定. 而数据值是存储到内存中的,有时变量会重新赋值即绑定其他数据值,而使得原本的数据值无法通过变 ...

  5. 垃圾回收机制GC知识再总结兼谈如何用好GC

    一.为什么需要GC 应用程序对资源操作,通常简单分为以下几个步骤: 1.为对应的资源分配内存 2.初始化内存 3.使用资源 4.清理资源 5.释放内存 应用程序对资源(内存使用)管理的方式,常见的一般 ...

  6. 垃圾回收机制GC知识再总结兼谈如何用好GC(转)

    作者:Jeff Wong 出处:http://jeffwongishandsome.cnblogs.com/ 本文版权归作者和博客园共有,欢迎围观转载.转载时请您务必在文章明显位置给出原文链接,谢谢您 ...

  7. python垃圾回收机制与小整数池

    python垃圾回收机制 当引用计数为0时,python会删除这个值. 引用计数 x = 10 y = x del x print(y) 10 引用计数+1,引用计数+1,引用计数-1,此时引用计数为 ...

  8. python垃圾回收机制:引用计数 VS js垃圾回收机制:标记清除

    js垃圾回收机制:标记清除 Js具有自动垃圾回收机制.垃圾收集器会按照固定的时间间隔周期性的执行. JS中最常见的垃圾回收方式是标记清除. 工作原理 当变量进入环境时,将这个变量标记为"进入 ...

  9. 垃圾回收机制GC知识再总结兼谈如何用好GC(其他信息: 内存不足)

    来源 图像操作,易内存泄露,边界像素 一.为什么需要GC 应用程序对资源操作,通常简单分为以下几个步骤: 1.为对应的资源分配内存 2.初始化内存 3.使用资源 4.清理资源 5.释放内存 应用程序对 ...

随机推荐

  1. phpcms v9手机门户配置方法

    一.确定一个域名作为你手机wap站点的访问域名,例如:http://m.tezhengzong.com. 接下来在域名管理系统中简析这个域名到你的服务器地址. 二.修改\caches\configs\ ...

  2. asp.net页面中的Console.WriteLine结果如何查看

    其实用Console.WriteLine("xxxxx"),在asp.net Web程序,在输出窗口是不会输出结果的,应该用Debug.WriteLine("xxxxx& ...

  3. asp.net Forms登录核心方法

    登录核心方法: private void Signin(string curUserId) { System.Web.Security.FormsAuthenticationTicket tk = , ...

  4. hadoop worldcount小程序

    首先在hadoop中建立input文件夹放几个文件,里边写点东西.比如我放了三个,分别写的是 第一个 hello hadoop bye hadoop 第二个 hello world bye world ...

  5. springMVC前后台数据交互

    假设项目需求是在springMVC框架下,后台要传送一个list到前台,那我们就要做以下几个步骤: 1 在web.xml文件中进行springMVC的配置: <?xml version=&quo ...

  6. 利用 spring 的 task:scheduled-tasks 执行定期任务

    ref是工作类 method是工作类中要执行的方法 initial-delay是任务第一次被调用前的延时,单位毫秒 fixed-delay是上一个调用完成后再次调用的延时 fixed-rate是上一个 ...

  7. BZOJ4399 魔法少女LJJ(线段树合并)

    注意到只有增加点/合并的操作.这些操作都可以用线段树完成,于是线段树合并一发就好了.注意乘积大小直接比较肯定会炸,取个对数即可.数据中存在重边. #include<iostream> #i ...

  8. NOIP临考经验【转】

    NOIP临考经验 1.提前15分钟入场,此时静坐调整心态,适当的深呼吸 2.打开编辑器并调整为自己喜欢的界面 3.熟悉文件目录,写好准确无误的代码模板 4.压缩包或许还不能解压,但是文件名已经可以知道 ...

  9. Powershell快速入门

    Powershell快速入门 来源: https://blog.csdn.net/u011054333/article/details/72567590 https://blog.csdn.net/u ...

  10. 周记【距gdoi:117天】

    国庆被“吞”了 图论还剩下平面图.分层图.欧拉图…… 是现实太残酷还是自己兴趣不够? 努力吧.