这篇文章主要介绍了如何使用Python实现计算对象的内存大小,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
具体如下:
一般的sys.getsizeof()显示不了复杂的字典。
查看类中的内容:
def dump(obj):
for attr in dir(obj):#dir显示类的所有方法
print(" obj.%s = %r" % (attr, getattr(obj, attr)))
这里用递归调用所有对象的getsizeof:
def get_size(obj, seen=None):
# From https://goshippo.com/blog/measure-real-size-any-python-object/
# Recursively finds size of objects
size = sys.getsizeof(obj)
if seen is None:
seen = set()
obj_id = id(obj)
if obj_id in seen:
return 0
# Important mark as seen *before* entering recursion to gracefully handle
# self-referential objects
seen.add(obj_id)
if isinstance(obj, dict):
size += sum([get_size(v, seen) for v in obj.values()])
size += sum([get_size(k, seen) for k in obj.keys()])
elif hasattr(obj, '__dict__'):
size += get_size(obj.__dict__, seen)
elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):
size += sum([get_size(i, seen) for i in obj])
return size
感谢你能够认真阅读完这篇文章,希望小编分享的“如何使用Python实现计算对象的内存大小”这篇文章对大家有帮助,同时也希望大家多多支持天达云,关注天达云行业资讯频道,更多相关知识等着你来学习!