gpt4 book ai didi

python - 在 Python 中准确测量对象大小 - Sys.GetSizeOf 不起作用

转载 作者:IT王子 更新时间:2023-10-28 23:36:01 34 4
gpt4 key购买 nike

我试图准确/明确地找到 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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com