← 中文资源

简体中文版本

getsizeof 只量对象本身不含内容

getsizeof 只报告单个对象自身的字节数(含头不含内容):嵌套容器实验显示外层列表只存指针,真正的内存开销在它引用的子对象里。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

empty list: 56
list of 1000: 8056
empty dict: 64
dict with 1000 keys: 36952
empty string: 49
1000-char string: 1049
outer list bytes: 72 | referenced children bytes: 16112
outer is a tiny fraction: True

实现说明

各个操作都建立在顶层绑定之上:nested、outer、children。

使用要点

  • 跑完文件,输出里会留下标记——empty list:、list of 1000:、empty dict:。

常见问题

需要安装第三方包吗?

不需要。只使用语言和平台的内建 API,粘贴进项目即可使用,无需安装任何东西。 全部导入都来自标准库:sys。 状态都挂在模块顶层:nested、outer、children。

代码示例

import sys

# getsizeof reports ONE object's own storage in bytes — the container header
# included, but referenced contents excluded
print("empty list:", sys.getsizeof([]))
print("list of 1000:", sys.getsizeof(list(range(1000))))
print("empty dict:", sys.getsizeof({}))
print("dict with 1000 keys:", sys.getsizeof({i: i for i in range(1000)}))

# The same rule holds for strings and tuples
print("empty string:", sys.getsizeof(""))
print("1000-char string:", sys.getsizeof("x" * 1000))

# Nesting proves the exclusion: the outer list only stores two pointers,
# while the children it references account for almost all real memory
nested = [list(range(1000)), list(range(1000))]
outer = sys.getsizeof(nested)
children = sys.getsizeof(nested[0]) + sys.getsizeof(nested[1])
print("outer list bytes:", outer, "| referenced children bytes:", children)
print("outer is a tiny fraction:", outer < children / 10)