sizeof
函数是 Python 的 sys
模块中的一个功能,它可以用来估计 Python 对象在内存中所占用的字节大小
sys
模块:import sys
sys.getsizeof()
函数获取对象的内存大小。例如,要获取一个列表的内存大小,可以这样做:my_list = [1, 2, 3, 4, 5]
size_of_list = sys.getsizeof(my_list)
print("Size of the list:", size_of_list, "bytes")
def get_total_sizeof(obj, seen=None):
if seen is None:
seen = set()
obj_id = id(obj)
if obj_id in seen:
return 0
seen.add(obj_id)
size = sys.getsizeof(obj)
if isinstance(obj, (list, tuple, set, frozenset)):
size += sum([get_total_sizeof(x, seen) for x in obj])
elif isinstance(obj, dict):
size += sum([get_total_sizeof(k, seen) + get_total_sizeof(v, seen) for k, v in obj.items()])
elif hasattr(obj, '__dict__'):
size += get_total_sizeof(obj.__dict__, seen)
elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):
size += sum([get_total_sizeof(x, seen) for x in obj])
return size
my_dict = {'a': 1, 'b': 2, 'c': [1, 2, 3]}
total_size = get_total_sizeof(my_dict)
print("Total size of the dictionary:", total_size, "bytes")
请注意,sizeof
函数提供的大小估计值可能并不完全准确,因为它不会考虑到某些 Python 实现或操作系统的特定细节。然而,在大多数情况下,它仍然是一个有用的工具,可以帮助你了解对象在内存中的大致占用情况。