我试图准确/明确地找到 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()
Output:
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尝试通过对各个 sizeof 求和来确定大小的方法,但这并没有产生任何不同的结果:
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
仅返回代表数据的对象结构的大小。因此,例如,如果您有一个不断向其添加元素的动态数组,sys.getsizeof(my_array)
只会显示底座的大小DynamicArray
对象,而不是其元素占用的不断增长的内存大小。
pympler.asizeof.asizeof() https://pympler.readthedocs.io/en/stable/library/asizeof.html#pympler.asizeof.asizeof给出物体的大致完整尺寸,可能对您来说更准确。
from pympler import asizeof
asizeof.asizeof(my_object) # should give you the full object size
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)