python

Python中sizeof函数对不同类型对象的计算方式

小樊
81
2024-08-27 12:33:16
栏目: 编程语言

在 Python 中,没有名为 sizeof 的内置函数。但是,您可以使用 sys.getsizeof() 函数来获取一个对象(如字符串、列表或字典)所占用的内存大小(以字节为单位)。

sys.getsizeof() 函数只返回对象本身所占用的内存大小,而不包括其子对象(例如,列表中的元素或字典中的键和值)所占用的内存。要计算一个对象及其所有子对象所占用的总内存大小,您需要编写一个递归函数。

以下是一个示例,展示了如何使用 sys.getsizeof() 函数计算不同类型对象的内存大小:

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 集合来跟踪已经计算过的对象。

0
看了该问题的人还看了