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


当前回答

如果性能不是问题,最简单的解决方案是pickle和测量:

import pickle

data = ...
len(pickle.dumps(data))

其他回答

我自己也遇到过很多次这个问题,我写了一个小函数(受到@aaron-hall的回答的启发)和测试,它完成了我所期望的sys。Getsizeof to do:

https://github.com/bosswissam/pysize

如果你对背景故事感兴趣,这就是

编辑:附上下面的代码以方便参考。要查看最新的代码,请检查github链接。

    import sys

    def get_size(obj, seen=None):
        """Recursively finds size of objects"""
        size = sys.getsizeof(obj)
        if seen is None:
            seen = set()
        obj_id = id(obj)
        if obj_id in seen:
            return 0
        # Important mark as seen *before* entering recursion to gracefully handle
        # self-referential objects
        seen.add(obj_id)
        if isinstance(obj, dict):
            size += sum([get_size(v, seen) for v in obj.values()])
            size += sum([get_size(k, seen) for k in obj.keys()])
        elif hasattr(obj, '__dict__'):
            size += get_size(obj.__dict__, seen)
        elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):
            size += sum([get_size(i, seen) for i in obj])
        return size

对于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

您可以使用下面提到的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")

如果性能不是问题,最简单的解决方案是pickle和测量:

import pickle

data = ...
len(pickle.dumps(data))

用系统就行了。sys模块中定义的Getsizeof函数。

sys.getsizeof(object[, default]): Return the size of an object in bytes. The object can be any type of object. All built-in objects will return correct results, but this does not have to hold true for third-party extensions as it is implementation specific. Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to. The default argument allows to define a value which will be returned if the object type does not provide means to retrieve the size and would cause a TypeError. getsizeof calls the object’s __sizeof__ method and adds an additional garbage collector overhead if the object is managed by the garbage collector. See recursive sizeof recipe for an example of using getsizeof() recursively to find the size of containers and all their contents.

python 3.0中的用法示例:

>>> import sys
>>> x = 2
>>> sys.getsizeof(x)
24
>>> sys.getsizeof(sys.getsizeof)
32
>>> sys.getsizeof('this')
38
>>> sys.getsizeof('this also')
48

如果你在python < 2.6并且没有sys. exe。Getsizeof可以使用这个扩展模块。但从来没用过。