【发布时间】:2016-11-01 09:30:11
【问题描述】:
from guppy import hpy
hp = hpy()
class Demo(object):
__slots__ = ('v0', 'v1')
def __init__(self, v0, v1):
self.v0 = v0
self.v1 = v1
from array import array
value = 1.01
ar = array('f')
ar2 = array('f')
for i in range(5000000):
ar.append(value + i)
ar2.append(value + i * 0.1 + i * 0.01 + i * 0.001 + i * 0.0001 + i * 0.000001)
a = []
for i in range(5000000):
vex = Demo(ar[i], ar[2])
a.append(vex)
print "Heap at the end of the functionn", hp.heap()
这是输出:
Heap at the end of the functionn Partition of a set of 15063247 objects. Total size = 650251664 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 5000000 33 320000000 49 320000000 49 __main__.Demo
1 10000108 66 240002592 37 560002592 86 float
2 368 0 42008896 6 602011488 93 list
3 2 0 40000112 6 642011600 99 array.array
4 28182 0 2214784 0 644226384 99 str
5 12741 0 1058448 0 645284832 99 tuple
6 189 0 669624 0 645954456 99 dict of module
7 371 0 588104 0 646542560 99 dict (no owner)
8 258 0 509232 0 647051792 100 dict of sip.wrappertype
9 3176 0 406528 0 647458320 100 types.CodeType
我想知道为什么 Demo 类要消耗这么多内存。因为 Demo 类只保留了对浮点数的引用,所以它不会复制浮点值。
getSizeOf(Demo) # 984
50W 的 Demo 类可能只消耗内存:984*50W=40215176,但现在需要消耗 320000000。
难以置信,为什么?
【问题讨论】:
-
984 乘以 5000 万是 4920000000,而不是 40215176。
标签: python python-2.7 memory