在 Python 中,沒有名為 sizeof
的內置函數。但是,您可以使用 sys.getsizeof()
函數來獲取一個對象(如字符串、列表或字典)所占用的內存大?。ㄒ宰止潪閱挝唬?。
sys.getsizeof()
函數只返回對象本身所占用的內存大小,而不包括其子對象(例如,列表中的元素或字典中的鍵和值)所占用的內存。要計算一個對象及其所有子對象所占用的總內存大小,您需要編寫一個遞歸函數。
以下是一個示例,展示了如何使用 sys.getsizeof()
函數計算不同類型對象的內存大?。?/p>
import sys
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(i, seen) for i in obj)
return size
# 示例
string = "Hello, world!"
list_obj = [1, 2, 3, 4, 5]
dict_obj = {'a': 1, 'b': 2, 'c': 3}
print("String memory size:", get_total_sizeof(string))
print("List memory size:", get_total_sizeof(list_obj))
print("Dictionary memory size:", get_total_sizeof(dict_obj))
請注意,這個示例中的 get_total_sizeof()
函數會遞歸地計算對象及其子對象所占用的內存大小。這可能會導致重復計算相同的子對象,因此我們使用 seen
集合來跟蹤已經計算過的對象。