试一下
>>> from pympler import tracker
>>> import random
>>> tr = tracker.SummaryTracker()
>>> a = [[random.random() for i in range(2000)] for i in range(2000)]
>>> tr.print_diff()
types | # objects | total size
========================================================== | =========== | ============
float | 4000000 | 91.55 MB
list | 4286 | 31.82 MB
str | 2035 | 109.42 KB
dict | 86 | 87.34 KB
int | 233 | 5.46 KB
<class 'pyreadline.lineeditor.lineobj.ReadLineTextBuffer | 84 | 4.59 KB
wrapper_descriptor | 9 | 648 B
unicode | 5 | 260 B
getset_descriptor | 4 | 256 B
member_descriptor | 3 | 192 B
weakref | 2 | 160 B
code | 1 | 128 B
function (store_info) | 1 | 112 B
cell | 2 | 96 B
tuple | 0 | 8 B
>>> import gc
>>> gc.collect()
>>> from sys import getsizeof
>>> getsizeof(a)
16560
用getsizeof(a) 取到的只是a一个list的object的大小 实际的大小要加上a里的4000000个float和2000个list的大小 所以这个2000 * 2000的list大小应该是120多mb
gc也没什么好collect的
想要占的少一点 最简单的方法是 用Numpy
>>> tr = tracker.SummaryTracker()
>>> a = array([[random.random() for i in range(2000)] for i in range(2000)])
>>> tr.print_diff()
types | # objects | total size
========================================================== | =========== | ============
numpy.ndarray | 1 | 30.52 MB
list | 3586 | 351.42 KB
str | 3315 | 178.17 KB
dict | 93 | 94.45 KB
int | 352 | 8.25 KB
<class 'pyreadline.lineeditor.lineobj.ReadLineTextBuffer | 91 | 4.98 KB
wrapper_descriptor | 9 | 648 B
unicode | 5 | 260 B
getset_descriptor | 4 | 256 B
weakref | 3 | 240 B