获取python对象占用空间的大小

2023-01-31 03:01:38 对象 获取 占用

原文:Http://stackoverflow.com/questions/449560/how-do-i-determine-the-size-of-an-object-in-python

 import sys

函数原型:

 

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.

返回一个对象所占用的字节大小。 对象可以是任何类型的对象,所有内置对象将返回正确的结果;但这并不能保证对第三方扩展总返回正确的结果,因为该函数是特定的实现


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.

default参数允许定义一个值,如果指定对象不提供获取大小的方法并会导致TypeError 则该默认值将被返回


getsizeof calls the object’s __sizeof__ method and adds an additional garbage collector overhead if the object is managed by the garbage collector.

 

 

getsizeof调用该对象的__sizeof__方法,如果对象是由垃圾回收器管理则会增加了一个额外的垃圾收集器的开销。

下面是在python3.0中的用法:

Usage example, in Python 3.0:

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

If you are in python < 2.6 and don't have sys.getsizeof you can use this extensive module instead

如果python版本低于2.6而没有sys。getsizeof方法,那可以从下面的地址获取第三方的模块作为替代:

http://code.activestate.com/recipes/546530/

 

 

 

相关文章