我有一个python类"foo",其中包含:
假设没有反向引用(循环),是否有一种简单的方法来衡量"foo"对象的总内存使用量?
基本上,我正在寻找"sys.getsizeof" 的递归版本
少数的,我碰到的工具包括:heapy,objgraph和GC,但我不认为任何人都能够胜任工作(我可以在此进行校正)
建议赞赏!
我想计算一个对象使用的内存.sys.getsizeof很好,但很浅(例如,在列表上调用,它不包括列表元素占用的内存).
我想写一个通用的"深层"版本sys.getsizeof.我理解"深层"的定义有些含糊不清; 我很满意后面copy.deepcopy的定义.
这是我的第一次尝试:
def get_deep_sizeof(x, level=0, processed=None):
if processed is None:
# we're here only if this function is called by client code, not recursively
processed = set()
processed.add(id(x))
mem = sys.getsizeof(x)
if isinstance(x, collections.Iterable) and not isinstance(x, str):
for xx in x:
if id(xx) in processed:
continue
mem += get_deep_sizeof(xx, level+1, processed)
if isinstance(x, dict):
mem += get_deep_sizeof(x[xx], level+1, processed)
return mem
Run Code Online (Sandbox Code Playgroud)
它遇到两个已知问题,以及未知数量未知的问题:
in,并硬编码字典的情况(包括值,而不仅仅是键).显然,这不适用于像字典这样的其他类.str(这是一个可迭代的,但没有任何其他对象的链接).如果有更多这样的对象,这将会破坏. …