如何在 Python 中获取对象在内存中占用的大小?
最佳答案
只需使用 sys.getsizeof
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.
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 aTypeError
.
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.getsizeof
你可以使用 this extensive module反而。不过没用过。
关于python - 如何确定 Python 中对象的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/449560/