python的内存回收机制即gc模块讲解
最后容易造成内存问题的通常就是全局单例、全局缓存、长期存活的对象
引用计数(主要), 标记清除, 分代收集(辅助)
引用计数为0则会被gc回收。标记删除可以解决循环引用的问题。分代:0代--年轻代;1代--中年代;2代--老年代,存活越久被回收的频率越低。
通过gc机制基本解决内存回收的问题。
不要轻易实现对象的__del__方法,和循环引用一起使用容易造成内存泄露,无法回收
gc模块包括如下函数和属性:
gc.disable()关闭自动的垃圾回收,改为手动;
gc.get_count()查看0、1、2代的数量(创建的对象数量-销毁的对象数量)
gc.get_threshold()查看0、1、2代的阈值
gc.collect(*args, **kwargs)手动执行垃圾回收,参数可以为0、1、2,表示回收指定代的垃圾;没有参数,表示0、1、2代全部回收,返回不可达的对象数量,不可达的对象也是要被清楚的对象,会被标记清除
gc.set_debug(DEBUG_COLLECTABLE|DEBUG_LEAK|DEBUG_SAVEALL|DEBUG_STATS|DEBUG_UNCOLLECTABLE) 把所有的debug开关打开。估计后端的C语音是根据8个bit位来判断debug开关功能的。
sys.getrefcount(a)查看a的引用计数
直接查看源代码说明:
def is_tracked(*args, **kwargs): # real signature unknown
"""
Returns true if the object is tracked by the garbage collector.
Simple atomic objects will return false.
"""
pass
所以a=2没有被tracked,a=[2,2]被tracked
# encoding: utf-
# module gc
# from (built-in)
# by generator 1.146
"""
This module provides access to the garbage collector for reference cycles. enable() -- Enable automatic garbage collection.
disable() -- Disable automatic garbage collection.
isenabled() -- Returns true if automatic collection is enabled.
collect() -- Do a full collection right now.
get_count() -- Return the current collection counts.
get_stats() -- Return list of dictionaries containing per-generation stats.
set_debug() -- Set debugging flags.
get_debug() -- Get debugging flags.
set_threshold() -- Set the collection thresholds.
get_threshold() -- Return the current the collection thresholds.
get_objects() -- Return a list of all objects tracked by the collector.
is_tracked() -- Returns true if a given object is tracked.
get_referrers() -- Return the list of objects that refer to an object.
get_referents() -- Return the list of objects that an object refers to.
freeze() -- Freeze all tracked objects and ignore them for future collections.
unfreeze() -- Unfreeze all objects in the permanent generation.
get_freeze_count() -- Return the number of objects in the permanent generation.
"""
# no imports # Variables with simple values DEBUG_COLLECTABLE =
DEBUG_LEAK =
DEBUG_SAVEALL =
DEBUG_STATS =
DEBUG_UNCOLLECTABLE = # functions def collect(*args, **kwargs): # real signature unknown
"""
Run the garbage collector. With no arguments, run a full collection. The optional argument
may be an integer specifying which generation to collect. A ValueError
is raised if the generation number is invalid. The number of unreachable objects is returned.
"""
pass def disable(*args, **kwargs): # real signature unknown
""" Disable automatic garbage collection. """
pass def enable(*args, **kwargs): # real signature unknown
""" Enable automatic garbage collection. """
pass def freeze(*args, **kwargs): # real signature unknown
"""
Freeze all current tracked objects and ignore them for future collections. This can be used before a POSIX fork() call to make the gc copy-on-write friendly.
Note: collection before a POSIX fork() call may free pages for future allocation
which can cause copy-on-write.
"""
pass def get_count(*args, **kwargs): # real signature unknown
""" Return a three-tuple of the current collection counts. """
pass def get_debug(*args, **kwargs): # real signature unknown
""" Get the garbage collection debugging flags. """
pass def get_freeze_count(*args, **kwargs): # real signature unknown
""" Return the number of objects in the permanent generation. """
pass def get_objects(*args, **kwargs): # real signature unknown
""" Return a list of objects tracked by the collector (excluding the list returned). """
pass def get_referents(*objs): # real signature unknown; restored from __doc__
"""
get_referents(*objs) -> list
Return the list of objects that are directly referred to by objs.
"""
return [] def get_referrers(*objs): # real signature unknown; restored from __doc__
"""
get_referrers(*objs) -> list
Return the list of objects that directly refer to any of objs.
"""
return [] def get_stats(*args, **kwargs): # real signature unknown
""" Return a list of dictionaries containing per-generation statistics. """
pass def get_threshold(*args, **kwargs): # real signature unknown
""" Return the current collection thresholds. """
pass def isenabled(*args, **kwargs): # real signature unknown
""" Returns true if automatic garbage collection is enabled. """
pass def is_tracked(*args, **kwargs): # real signature unknown
"""
Returns true if the object is tracked by the garbage collector. Simple atomic objects will return false.
"""
pass def set_debug(*args, **kwargs): # real signature unknown
"""
Set the garbage collection debugging flags. flags
An integer that can have the following bits turned on:
DEBUG_STATS - Print statistics during collection.
DEBUG_COLLECTABLE - Print collectable objects found.
DEBUG_UNCOLLECTABLE - Print unreachable but uncollectable objects
found.
DEBUG_SAVEALL - Save objects to gc.garbage rather than freeing them.
DEBUG_LEAK - Debug leaking programs (everything but STATS). Debugging information is written to sys.stderr.
"""
pass def set_threshold(threshold0, threshold1=None, threshold2=None): # real signature unknown; restored from __doc__
"""
set_threshold(threshold0, [threshold1, threshold2]) -> None Sets the collection thresholds. Setting threshold0 to zero disables
collection.
"""
pass def unfreeze(*args, **kwargs): # real signature unknown
"""
Unfreeze all objects in the permanent generation. Put all objects in the permanent generation back into oldest generation.
"""
pass # classes class __loader__(object):
"""
Meta path import for built-in modules. All methods are either class or static methods to avoid the need to
instantiate the class.
"""
@classmethod
def create_module(cls, *args, **kwargs): # real signature unknown
""" Create a built-in module """
pass @classmethod
def exec_module(cls, *args, **kwargs): # real signature unknown
""" Exec a built-in module """
pass @classmethod
def find_module(cls, *args, **kwargs): # real signature unknown
"""
Find the built-in module. If 'path' is ever specified then the search is considered a failure. This method is deprecated. Use find_spec() instead.
"""
pass @classmethod
def find_spec(cls, *args, **kwargs): # real signature unknown
pass @classmethod
def get_code(cls, *args, **kwargs): # real signature unknown
""" Return None as built-in modules do not have code objects. """
pass @classmethod
def get_source(cls, *args, **kwargs): # real signature unknown
""" Return None as built-in modules do not have source code. """
pass @classmethod
def is_package(cls, *args, **kwargs): # real signature unknown
""" Return False as built-in modules are never packages. """
pass @classmethod
def load_module(cls, *args, **kwargs): # real signature unknown
"""
Load the specified module into sys.modules and return it. This method is deprecated. Use loader.exec_module instead.
"""
pass def module_repr(module): # reliably restored by inspect
"""
Return repr for the module. The method is deprecated. The import machinery does the job itself.
"""
pass def __init__(self, *args, **kwargs): # real signature unknown
pass __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""list of weak references to the object (if defined)""" __dict__ = None # (!) real value is '' # variables with complex values callbacks = [] garbage = [] __spec__ = None # (!) real value is ''
参考:
1、https://foofish.net/python-gc.html
2、
python的内存回收机制即gc模块讲解的更多相关文章
- 【Python】 垃圾回收机制和gc模块
垃圾回收机制和gc模块 Py的一个大好处,就是灵活的变量声明和动态变量类型.虽然这使得学习py起来非常方便快捷,但是同时也带来了py在性能上的一些不足.其中相关内存比较主要的一点就是py不会对已经销毁 ...
- python的内存回收机制
变量相当于门牌号,当门牌没有了,即函数的引用都没有调用了,内存的数据就会被清除掉. python内有个定时器,定期的会刷新,如果发现内存中数据被引用了,就会被回收,这个就是内存的回收机制 ...
- Python垃圾回收机制及gc模块详解:内存泄露的例子
标记清理是用来解决循环引用的.分代回收针对所有的新创建即进入0代的对象和进入1.2代的对象..这样就解释了python“引用计数为主.标记清理+分代回收为辅”的垃圾回收原理,因为循环引用毕竟是少数情况 ...
- Python之美[从菜鸟到高手]--Python垃圾回收机制及gc模块详解
http://blog.csdn.net/yueguanghaidao/article/details/11274737
- python 的内存回收,及深浅Copy详解
一.python中的变量及引用 1.1 python中的不可变类型: 数字(num).字符串(str).元组(tuple).布尔值(bool<True,False>) 接下来我们讲完后你就 ...
- 详解python的垃圾回收机制
python的垃圾回收机制 一.引子 我们定义变量会申请内存空间来存放变量的值,而内存的容量是有限的,当一个变量值没有用了(简称垃圾)就应该将其占用的内存空间给回收掉,而变量名是访问到变量值的唯一方式 ...
- python中垃圾回收机制
Python垃圾回收机制详解 一.垃圾回收机制 Python中的垃圾回收是以引用计数为主,分代收集为辅.引用计数的缺陷是循环引用的问题.在Python中,如果一个对象的引用数为0,Python虚拟 ...
- python的垃圾回收机制和析构函数__del__
析构函数__del__定义:在类里定义,如果不定义,Python 会在后台提供默认析构函数. 析构函数__del__调用: A.使用del 显式的调用析构函数删除对象时:del对象名: class F ...
- python之垃圾回收机制
一.前言 Python 是一门高级语言,使用起来类似于自然语言,开发的时候自然十分方便快捷,原因是Python在背后为我们默默做了很多事情,其中一件就是垃圾回收,来解决内存管理,内存泄漏的问题. 内存 ...
随机推荐
- 【LOJ】#2056. 「TJOI / HEOI2016」序列
题解 这个我们处理出来每一位能变化到的最大值和最小值,包括自身 然后我们发现 \(f[i] = max(f[i],f[j] + 1) (mx[j] <= a[i] && a[j] ...
- redhat重置密码
当忘记虚拟机密码时怎么办? 1.启动虚拟机,当虚拟机显示输入enter启动时输入e 2.再次用上下键选中你平时启动linux的那一项(类似于kernel /boot/vmlinuz-2.4.18-14 ...
- mysql的第一个程序
每次写java链接数据怎么写,这一次做一个总结,方便参考. 1.在mysql上下载mysql驱动jar包 2.下载的驱动包 3.程序目录 4.程序 package mysqlTest; import ...
- JAVAEE——宜立方商城01:电商行业的背景、商城系统架构、后台工程搭建、SSM框架整合
1. 学习计划 第一天: 1.电商行业的背景. 2.宜立方商城的系统架构 a) 功能介绍 b) 架构讲解 3.工程搭建-后台工程 a) 使用maven搭建工程 b) 使用maven的tomcat插件启 ...
- Openstack_通用模块_Oslo_vmware 创建 vCenter 虚拟机快照
创建虚拟机快照 vSphere Create Snapshot 文档 Snapshot 是虚拟机磁盘文件(VMDK)在某个点及时的复本.包含了虚拟机所有虚拟磁盘上的数据状态和这个虚拟机的电源状态(on ...
- dhcp 提示could not load neutron.agent
错误日志如下: N版存在问题,其它版本不知道 解决方法(代码问题): /usr/lib/python2.7/site-packages/neutron/common/utils.py 在这个方法上(d ...
- [HDU6212]Zuma
题目大意: 祖玛游戏. 给你一个01串,你可以往里面加一些0或1,如果连续的0或1超过3个,那么就可以消去.问消去所有的珠子至少要加几个珠子. 思路: 区间DP. 首先把原来的01串,改成存储连续的同 ...
- 【8.13校内测试】【DP】【按除数分类】【二分】
感觉今天状态不太好啊一大早就很困,t1卡得有点久,以为三道题都是这个难度,结果难度完全是倒着排的啊!!在dp和数学上还得多练题!! 很像背包的一道DP??先不考虑树的结构,给每个点都先分配一个度数,剩 ...
- hdu 3879 方案选择
每日一水--- #include <cstdio> #include <cstring> #include <vector> #define oo 0x3f3f3f ...
- Python编程练习题学习汇总
实例一:数学计算 简述:这里有四个数字,分别是:1.2.3.4提问:能组成多少个互不相同且无重复数字的三位数?各是多少? Python解题思路分析:可填在百位.十位.个位的数字都是1.2.3.4.组成 ...