【发布时间】:2012-12-21 22:01:39
【问题描述】:
我想计算一个对象使用的内存。 sys.getsizeof 很棒,但很浅(例如,在列表上调用,它不会包括列表元素占用的内存)。
我想写一个通用的“深度”版本的sys.getsizeof。我知道“深度”的定义有些模糊;我对definition followed by 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
它存在两个已知问题,以及未知数量的未知问题:
- 我不知道如何以捕获所有链接对象的方式遍历通用容器。因此,我使用
in进行了迭代,并对字典的大小写进行了硬编码(包括值,而不仅仅是键)。显然,这不适用于字典等其他类。 - 我不得不硬编码排除
str(这是一个可迭代的,但没有指向任何其他对象的链接)。同样,如果有更多这样的对象,这将中断。
我怀疑使用in 不是一个好主意,但我不确定还能做什么。
【问题讨论】:
标签: python memory python-3.x deep-copy