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 實現或操作系統的特定細節。然而,在大多數情況下,它仍然是一個有用的工具,可以幫助你了解對象在內存中的大致占用情況。