如何在Python中查找对象的大小?
可以使用sys.getsizeof()来查找占用内存中某些空间的特定对象的存储大小。此函数以字节为单位返回对象的大小。它最多需要两个参数,即对象本身。
注意:只考虑直接归因于对象的内存消耗,而不是它所引用的对象的内存消耗。
例子:
Input:
# Any Integer Value
sys.getsizeof(4)
Expected Output: 4 bytes (Size of integer is 4bytes)
Actual Output: 28 bytes
这是我们如何解释实际输出的方法。看看下表:Type of Object Actual Size Notes int 28 NA str 49 +1 per additional character (49+total length of characters) tuple 40 (Empty Tuple) +8 per additional item in tuple ( 40 + 8*total length of characters ) list 56 (Empty List) +8 per additional item in list ( 56 + 8*total length of characters ) set 216 0-4 take size of 216. 5-19 take size 728. 20th will take 2264 and so on… dict 232 0-5 takes size of 232. 6-10 size will be 360. 11th will take 640 and so on… func def 136 No attributes and default arguments
例子:
Python3
import sys
a = sys.getsizeof(12)
print(a)
b = sys.getsizeof('geeks')
print(b)
c = sys.getsizeof(('g', 'e', 'e', 'k', 's'))
print(c)
d = sys.getsizeof(['g', 'e', 'e', 'k', 's'])
print(d)
e = sys.getsizeof({1, 2, 3, 4})
print(e)
f = sys.getsizeof({1: 'a', 2: 'b', 3: 'c', 4: 'd'})
print(f)
输出:
28
54
88
104
224
240