gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:01:11 25 4
gpt4 key购买 nike

如何在 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 returncorrect results, but this does nothave to hold true for third-partyextensions as it is implementationspecific.

Only the memory consumption directly attributed to the object isaccounted for, not the memory consumption of objects it refers to.

The default argument allows to definea value which will be returned if theobject type does not provide means toretrieve the size and would cause aTypeError.

getsizeof calls the object’s__sizeof__ method and adds an additional garbage collector overheadif the object is managed by thegarbage 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com