- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我试图准确/明确地找到 Python 中两个不同类之间的大小差异。它们都是新的样式类,除了一个没有定义slots。我已经尝试了许多测试来确定它们的大小差异,但它们最终在内存使用方面总是相同的。
到目前为止,我已经尝试了 sys.GetSizeOf(obj) 和 heapy 的 heap() 函数,没有任何积极的结果。测试代码如下:
import sys
from guppy import hpy
class test3(object):
def __init__(self):
self.one = 1
self.two = "two variable"
class test4(object):
__slots__ = ('one', 'two')
def __init__(self):
self.one = 1
self.two = "two variable"
test3_obj = test3()
print "Sizeof test3_obj", sys.getsizeof(test3_obj)
test4_obj = test4()
print "Sizeof test4_obj", sys.getsizeof(test4_obj)
arr_test3 = []
arr_test4 = []
for i in range(3000):
arr_test3.append(test3())
arr_test4.append(test4())
h = hpy()
print h.heap()
输出:
Sizeof test3_obj 32
Sizeof test4_obj 32
Partition of a set of 34717 objects. Total size = 2589028 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 11896 34 765040 30 765040 30 str
1 3001 9 420140 16 1185180 46 dict of __main__.test3
2 5573 16 225240 9 1410420 54 tuple
3 348 1 167376 6 1577796 61 dict (no owner)
4 1567 5 106556 4 1684352 65 types.CodeType
5 68 0 105136 4 1789488 69 dict of module
6 183 1 97428 4 1886916 73 dict of type
7 3001 9 96032 4 1982948 77 __main__.test3
8 3001 9 96032 4 2078980 80 __main__.test4
9 203 1 90360 3 2169340 84 type
<99 more rows. Type e.g. '_.more' to view.>
这就是 Python 2.6.0 的全部内容。我还尝试覆盖类的 sizeof 方法,尝试通过对各个 sizeofs 求和来确定大小,但这并没有产生任何不同的结果:
class test4(object):
__slots__ = ('one', 'two')
def __init__(self):
self.one = 1
self.two = "two variable"
def __sizeof__(self):
return super(test4, self).__sizeof__() + self.one.__sizeof__() + self.two.__sizeof__()
覆盖 sizeof 方法的结果:
Sizeof test3_obj 80
Sizeof test4_obj 80
最佳答案
sys.getsizeof
返回一个比人们想象的更专业、更没用的数字。事实上,如果你将属性数增加到六个,你的 test3_obj 仍然是 32,但 test4_obj 会跳转到 48 个字节。这是因为 getsizeof 正在返回实现类型的 PyObject 结构的大小,对于 test3_obj 不包括保存属性的字典,但对于 test4_obj,属性不存储在字典中,它们存储在插槽中,所以它们被计入大小。
但是使用 __slots__
定义的类比没有使用的类占用更少的内存,这正是因为没有 dict 来保存属性。
为什么要覆盖 __sizeof__
?你真正想要完成什么?
关于python - 在 Python 中准确测量对象大小 - Sys.GetSizeOf 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11301295/
今天有小伙伴给我留言问到,try{...}catch(){...}是什么意思?它用来干什么? 简单的说 他们是用来捕获异常的 下面我们通过一个例子来详细讲解下
我正在努力提高网站的可访问性,但我不知道如何在页脚中标记社交媒体链接列表。这些链接指向我在 facecook、twitter 等上的帐户。我不想用 role="navigation" 标记这些链接,因
说现在是 6 点,我有一个 Timer 并在 10 点安排了一个 TimerTask。之后,System DateTime 被其他服务(例如 ntp)调整为 9 点钟。我仍然希望我的 TimerTas
就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用资料或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
我就废话不多说了,大家还是直接看代码吧~ ? 1
Maven系列1 1.什么是Maven? Maven是一个项目管理工具,它包含了一个对象模型。一组标准集合,一个依赖管理系统。和用来运行定义在生命周期阶段中插件目标和逻辑。 核心功能 Mav
我是一名优秀的程序员,十分优秀!