实现说明
各个操作都建立在顶层绑定之上: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)