sizeof 函数在 Python 中并不是内置函数,但我们可以通过 sys.getsizeof() 函数来获取对象所占用的内存大小。以下是一些使用场景:
sys.getsizeof() 函数,我们可以查看不同类型的对象所占用的内存大小。import sys# 获取字符串对象的内存占用string_memory = sys.getsizeof("Hello, world!")print(f"Memory used by string: {string_memory} bytes")# 获取列表对象的内存占用list_memory = sys.getsizeof([1, 2, 3, 4, 5])print(f"Memory used by list: {list_memory} bytes")比较数据结构:在选择合适的数据结构时,了解不同数据结构的内存占用情况是很有帮助的。例如,比较列表、元组和集合的内存占用。import syslist_memory = sys.getsizeof([1, 2, 3, 4, 5])tuple_memory = sys.getsizeof((1, 2, 3, 4, 5))set_memory = sys.getsizeof({1, 2, 3, 4, 5})print(f"Memory used by list: {list_memory} bytes")print(f"Memory used by tuple: {tuple_memory} bytes")print(f"Memory used by set: {set_memory} bytes")需要注意的是,sys.getsizeof() 函数只返回对象本身所占用的内存大小,而不包括对象中引用的其他对象所占用的内存。因此,在分析复杂对象的内存占用时,可能需要递归地计算子对象的内存占用。


