如何在Python中获得对象在内存中占用的大小?


当前回答

这可能比看起来要复杂得多,这取决于你想要如何计数。例如,如果您有一个int类型的列表,您是否需要包含对int类型引用的列表的大小?(即-列表,而不是包含在其中的内容),或者你想包括实际指向的数据,在这种情况下,你需要处理重复引用,以及如何防止重复计数当两个对象包含对同一对象的引用时。

您可能想要查看python内存分析器之一,例如pysizer,以查看它们是否满足您的需求。

其他回答

您可以使用下面提到的getSizeof()来确定对象的大小

import sys
str1 = "one"
int_element=5
print("Memory size of '"+str1+"' = "+str(sys.getsizeof(str1))+ " bytes")
print("Memory size of '"+ str(int_element)+"' = "+str(sys.getsizeof(int_element))+ " bytes")

对于numpy数组,getsizeof不起作用-对我来说,它总是出于某种原因返回40:

from pylab import *
from sys import getsizeof
A = rand(10)
B = rand(10000)

然后(在ipython中):

In [64]: getsizeof(A)
Out[64]: 40

In [65]: getsizeof(B)
Out[65]: 40

不过令人高兴的是,:

In [66]: A.nbytes
Out[66]: 80

In [67]: B.nbytes
Out[67]: 80000

下面是我根据之前对所有变量的列表大小的回答编写的一个快速脚本

for i in dir():
    print (i, sys.getsizeof(eval(i)) )

If you don't need the exact size of the object but roughly to know how big it is, one quick (and dirty) way is to let the program run, sleep for an extended period of time, and check the memory usage (ex: Mac's activity monitor) by this particular python process. This would be effective when you are trying to find the size of one single large object in a python process. For example, I recently wanted to check the memory usage of a new data structure and compare it with that of Python's set data structure. First I wrote the elements (words from a large public domain book) to a set, then checked the size of the process, and then did the same thing with the other data structure. I found out the Python process with a set is taking twice as much memory as the new data structure. Again, you wouldn't be able to exactly say the memory used by the process is equal to the size of the object. As the size of the object gets large, this becomes close as the memory consumed by the rest of the process becomes negligible compared to the size of the object you are trying to monitor.

Python 3.8(2019年第一季度)将改变sys. js的一些结果。getsizeof, Raymond Hettinger在此宣布:

Python容器在64位版本上要小8个字节。

tuple ()  48 -> 40       
list  []  64 ->56
set()    224 -> 216
dict  {} 240 -> 232

这是在议题33597和稻田直树(甲烷)围绕紧凑型PyGC_Head和PR 7043的工作之后

这个想法将PyGC_Head大小减少到两个单词。 目前,PyGC_Head包含三个单词;Gc_prev, gc_next和gc_refcnt。 收集时使用Gc_refcnt,用于尝试删除。 Gc_prev用于跟踪和取消跟踪。 因此,如果我们可以在试删除时避免跟踪/取消跟踪,gc_prev和gc_refcnt可以共享相同的内存空间。

参见commit d5c875b:

从PyGC_Head中移除一个Py_ssize_t成员。 所有GC跟踪的对象(例如元组,列表,dict)大小减少4或8字节。