在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. C#程序中SQL语句作为函数参数形式问题

    今天遇到一个神奇现象,目前正在写一个Demo,人事管理系统,首先肯定是初始化主页面,在初始化时,需要声明一个登陆窗体,但是当我在登陆窗体中填入登入名称和密码时直接就登陆成功了,但是发现我的status ...

  2. htm,html,xhtml,xml,xsl,dhtml,shtm和shtml的区分

    介绍一下htm,html,xhtml,xml,shtml的区分,以下内容来自百度后的知识整理. HTML和htm: HTML(Hypertext Markup Language)超文本传输语言,是ww ...

  3. StanFord 编程方法

    教程下载地址:http://www.yyets.com/resource/26208 定制工具下载地址:http://www.stanford.edu/class/cs106a/cgi-bin/cla ...

  4. 大数据Hadoop-2

    大数据Hadoop学习之搭建Hadoop平台(2.1) 关于大数据,一看就懂,一懂就懵. 大数据的发展也有些年头了,如今正走在风口浪尖上,作为小白,我也来凑一份热闹. 大数据经过多年的发展,有着不同的 ...

  5. BZOJ4484 JSOI2015最小表示(拓扑排序+bitset)

    考虑在每个点的出边中删除哪些.如果其出边所指向的点中存在某点能到达另一点,那么显然指向被到达点的边是没有用的.于是拓扑排序逆序处理,按拓扑序枚举出边,bitset维护可达点集合即可. #include ...

  6. React生命周期总结

    React的生命周期总共8个钩子,三个will,两个Did,一个RecciveProps,一个ShouldUpdate,一个render.分为三个阶段,分别是 装载 Mounting更新 Updati ...

  7. HDU1151:Air Raid(最小边覆盖)

    Air Raid Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Su ...

  8. Codeforces Round #525 (Div. 2)A. Ehab and another construction problem

    A. Ehab and another construction problem 题目链接:https://codeforc.es/contest/1088/problem/A 题意: 给出一个x,找 ...

  9. bzoj 3513 [MUTC2013]idiots FFT 生成函数

    [MUTC2013]idiots Time Limit: 20 Sec  Memory Limit: 128 MBSubmit: 806  Solved: 265[Submit][Status][Di ...

  10. 计算n阶行列式的模板

    之前在学习计数问题的时候也在网上找了很多关于行列式的资料 但是发现很多地方都只介绍2\3阶的情况 一些论文介绍的方法又看不懂 然后就一直耽搁着 今天恰好出到这样的题目 发现标算的代码简介明了 还挺开心 ...