python - 如何确定 Python 中对象的大小?

标签 python object memory memory-management sizeof

如何在 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 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.getsizeof 你可以使用 this extensive module反而。不过没用过。

关于python - 如何确定 Python 中对象的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/449560/

相关文章:

python - python Tkinter中的简单加载屏幕

python minidom混合元素属性

JavaScript 将值附加到对象

javascript - jQuery:展开 HTML 字符串中的元素

python - 使用 Python 在 ElasticSearch 中添加 @timestamp 字段

python - debian 7 上的 Kivy

javascript - 检索原型(prototype)属性时出现类型错误

作为对象的 JavaScript 词法环境

asp.net - IIS 工作进程使用大量内存?

java - 如何对tomcat进行端到端性能分析