走过山头,坐在夕阳勾勒的黄昏里,吹一缕向晚的凉风,听树叶婆娑着沙沙的声响。望着天边绯红的落日渐渐西沉,透过头顶的树隙,仍有一抹余温爬上微热的脸庞。
本文实例讲述了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程序设计有所帮助。
到此这篇关于Python实现计算对象的内存大小示例就介绍到这了。别遇到一点鸡毛蒜皮的事情就一蹶不振,你才多岁,怕什么困难无穷。更多相关Python实现计算对象的内存大小示例内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!