浅谈Python 对象内存占用


Posted in Python onJuly 15, 2016

一切皆是对象

在 Python 一切皆是对象,包括所有类型的常量与变量,整型,布尔型,甚至函数。 参见stackoverflow上的一个问题 Is everything an object in python like ruby

代码中即可以验证:

# everythin in python is object def fuction(): return print isinstance(True, object) print isinstance(0, object) print isinstance('a', object) print isinstance(fuction, object)

如何计算

Python 在 sys 模块中提供函数 getsizeof 来计算 Python 对象的大小。

sys.getsizeof(object[, default])

以字节(byte)为单位返回对象大小。 这个对象可以是任何类型的对象。 所以内置对象都能返回正确的结果 但不保证对第三方扩展有效,因为和具体实现相关。

......

getsizeof() 调用对象的 __sizeof__ 方法, 如果对象由垃圾收集器管理, 则会加上额外的垃圾收集器开销。

当然,对象内存占用与 Python 版本以及操作系统版本关系密切, 本文的代码和测试结果都是基于 windows7 32位操作系统。

import sys print sys.version

2.7.2 (default, Jun 24 2011, 12:21:10) [MSC v.1500 32 bit (Intel)]

基本类型

•布尔型

print 'size of True: %d' % (sys.getsizeof(True)) print 'size of False: %d' % (sys.getsizeof(False))

输出:

size of True: 12 size of False: 12

•整型

# normal integer print 'size of integer: %d' % (sys.getsizeof(1)) # long print 'size of long integer: %d' % (sys.getsizeof(1L)) print 'size of big long integer: %d' % (sys.getsizeof(100000L)) 输出:

size of integer: 12x size of long integer 1L: 14 size of long integer 100000L: 16

可以看出整型占用12字节,长整型最少占用14字节,且占用空间会随着位数的增多而变大。 在2.x版本,如果整型类型的值超出sys.maxint,则自动会扩展为长整型。而 Python 3.0 之后,整型和长整型统一为一种类型。

•浮点型

print 'size of float: %d' % (sys.getsizeof(1.0))

输出:

size of float: 16

浮点型占用16个字节。超过一定精度后会四舍五入。

参考如下代码:

print 1.00000000003 print 1.000000000005

输出:

1.00000000003 1.00000000001

•字符串

# size of string type print '\r\n'.join(["size of string with %d chars: %d" % (len(elem), sys.getsizeof(elem)) for elem in ["", "a", "ab"]]) # size of unicode string print '\r\n'.join(["size of unicode string with %d chars: %d" % (len(elem), sys.getsizeof(elem)) for elem in [u"", u"a", u"ab"]])

输出:

size of string with 0 chars: 21 size of string with 1 chars: 22 size of string with 2 chars: 23 size of unicode string with 0 chars: 26 size of unicode string with 1 chars: 28 size of unicode string with 2 chars: 30

普通空字符串占21个字节,每增加一个字符,多占用1个字节。Unicode字符串最少占用26个字节,每增加一个字符,多占用2个字节。

集合类型

•列表

# size of list type print '\r\n'.join(["size of list with %d elements: %d" % (len(elem), sys.getsizeof(elem)) for elem in [[], [0], [0,2], [0,1,2]]])

输出:

size of list with 0 elements: 36 size of list with 1 elements: 40 size of list with 2 elements: 44 size of list with 3 elements: 48

可见列表最少占用36个字节,每增加一个元素,增加4个字节。但要注意,sys.getsizeof 函数并不计算容器类型的元素大小。比如:

print 'size of list with 3 integers %d' % (sys.getsizeof([0,1,2])) print 'size of list with 3 strings %d' % (sys.getsizeof(['0','1','2']))

输出:

size of list with 3 integers 48 size of list with 3 strings 48

容器中保存的应该是对元素的引用。如果要准确计算容器,可以参考recursive sizeof recipe 。使用其给出的 total_size 函数:

print 'total size of list with 3 integers %d' % (total_size([0,1,2])) print 'total size of list with 3 strings %d' % (total_size(['0','1','2']))

输出为:

total size of list with 3 integers 84 total size of list with 3 strings 114

可以看出列表的空间占用为 基本空间 36 + (对象引用 4 + 对象大小) * 元素个数。

另外还需注意如果声明一个列表变量,则其会预先分配一些空间,以便添加元素时增加效率:

li = [] for i in range(0, 101): print 'list with %d integers size: %d, total_size: %d' % (i, getsizeof(li), total_size(li)) li.append(i)

•元组

基本与列表类似,但其最少占用为28个字节。

•字典

字典的情况相对复杂很多,具体当然要参考代码 dictobject.c, 另外 NOTES ON OPTIMIZING DICTIONARIES 非常值得仔细阅读。

基本情况可以参考[stackoverflow] 的问题 Python's underlying hash data structure for dictionaries 中的一些回答:

•字典最小拥有8个条目的空间(PyDict_MINSIZE);
•条目数小于50,000时,每次增长4倍;
•条目数大于50,000时,每次增长2倍;
•键的hash值缓存在字典中,字典调整大小后不会重新计算;

每接近2/3时,字典会调整大小。

以上这篇浅谈Python 对象内存占用就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python 正则表达式(转义问题)
Dec 15 Python
python 远程统计文件代码分享
May 14 Python
Python中处理字符串之endswith()方法的使用简介
May 18 Python
基于进程内通讯的python聊天室实现方法
Jun 28 Python
详解C++编程中一元运算符的重载
Jan 19 Python
Python中字符串的格式化方法小结
May 03 Python
如何利用python制作时间戳转换工具详解
Sep 12 Python
浅析Python四种数据类型
Sep 26 Python
解决Python中定时任务线程无法自动退出的问题
Feb 18 Python
使用Python创建简单的HTTP服务器的方法步骤
Apr 26 Python
Python如何将字符串转换为日期
Jul 31 Python
Python OpenCV超详细讲解读取图像视频和网络摄像头
Apr 02 Python
python发送邮件功能实现代码
Jul 15 #Python
Python中列表和元组的使用方法和区别详解
Dec 30 #Python
Python中的变量和作用域详解
Jul 13 #Python
在Python中通过threading模块定义和调用线程的方法
Jul 12 #Python
举例讲解Python编程中对线程锁的使用
Jul 12 #Python
使用Python编写一个最基础的代码解释器的要点解析
Jul 12 #Python
Python中使用bidict模块双向字典结构的奇技淫巧
Jul 12 #Python
You might like
PHP页面间参数传递的四种方法详解
2013/06/09 PHP
PHP的Yii框架中使用数据库的配置和SQL操作实例教程
2016/03/17 PHP
php使用Jpgraph创建3D饼形图效果示例
2017/02/15 PHP
PHP SESSION跨页面传递失败解决方案
2020/12/11 PHP
JScript中的undefined和"undefined"的区别
2007/03/08 Javascript
ExtJs grid行 右键菜单的两种方法
2010/06/19 Javascript
Iframe实现跨浏览器自适应高度解决方法
2014/09/02 Javascript
jQuery实现带玻璃流光质感的手风琴特效
2015/11/20 Javascript
Bootstrap表单布局
2016/07/19 Javascript
JavaScript实现三级联动菜单效果
2017/08/16 Javascript
JavaScript实现随机数生成器(去重)
2017/10/13 Javascript
nodejs多版本管理总结
2018/04/03 NodeJs
JavaScript实现简单动态进度条效果
2018/04/06 Javascript
axios简单实现小程序延时loading指示
2018/07/30 Javascript
手写Vue弹窗Modal的实现代码
2019/09/11 Javascript
[47:46]完美世界DOTA2联赛 Magma vs GXR 第三场 11.07
2020/11/10 DOTA
在Python的gevent框架下执行异步的Solr查询的教程
2015/04/16 Python
Python 转义字符详细介绍
2017/03/21 Python
如何使用VSCode愉快的写Python于调试配置步骤
2018/04/06 Python
python实现kNN算法识别手写体数字的示例代码
2019/08/16 Python
查看端口并杀进程python脚本代码
2019/12/17 Python
利用 Python ElementTree 生成 xml的实例
2020/03/06 Python
浅谈python的elementtree模块处理中文注意事项
2020/03/06 Python
keras.layer.input()用法说明
2020/06/16 Python
python给视频添加背景音乐并改变音量的具体方法
2020/07/19 Python
C#如何调用Word并打开一个Word文档
2013/05/08 面试题
什么是JNDI的上下文?如何初始化JNDI上下文
2012/03/10 面试题
会计专业大学生职业生涯规划范文
2014/01/11 职场文书
婚庆公司的创业计划书
2014/01/22 职场文书
金融事务专业求职信
2014/04/25 职场文书
领导干部民主生活会自我剖析材料范文
2014/09/20 职场文书
住房抵押登记委托书
2014/09/27 职场文书
公司合并协议书范本
2014/09/30 职场文书
2014年教育实习工作总结
2014/11/22 职场文书
2014年体育教师工作总结
2014/12/03 职场文书
贪污检举信范文
2015/03/02 职场文书