使用這個配方,取自:
http://code.activestate.com/recipes/577504-compute-memory-footprint-of-an-object-and-its-cont/
from __future__ import print_function
from sys import getsizeof, stderr
from itertools import chain
from collections import deque
try:
from reprlib import repr
except ImportError:
pass
def total_size(o, handlers={}, verbose=False):
""" Returns the approximate memory footprint an object and all of its contents.
Automatically finds the contents of the following builtin containers and
their subclasses: tuple, list, deque, dict, set and frozenset.
To search other containers, add handlers to iterate over their contents:
handlers = {SomeContainerClass: iter,
OtherContainerClass: OtherContainerClass.get_elements}
"""
dict_handler = lambda d: chain.from_iterable(d.items())
all_handlers = {tuple: iter,
list: iter,
deque: iter,
dict: dict_handler,
set: iter,
frozenset: iter,
}
all_handlers.update(handlers) # user handlers take precedence
seen = set() # track which object id's have already been seen
default_size = getsizeof(0) # estimate sizeof object without __sizeof__
def sizeof(o):
if id(o) in seen: # do not double count the same object
return 0
seen.add(id(o))
s = getsizeof(o, default_size)
if verbose:
print(s, type(o), repr(o), file=stderr)
for typ, handler in all_handlers.items():
if isinstance(o, typ):
s += sum(map(sizeof, handler(o)))
break
return s
return sizeof(o)
##### Example call #####
if __name__ == '__main__':
d = dict(a=1, b=2, c=3, d=[4,5,6,7], e='a string of chars')
print(total_size(d, verbose=True))
我試過這種方式,但是當你試圖得到一個列表的列表的大小,你得到的只是父列表中的大小,而不是與嵌套表總。 我不知道如果我編寫代碼來做遞歸,我會得到真正的內存使用。 – crandrades
@ user1847706在條目結尾處我將文檔鏈接到文檔中,有[請參閱recursive sizeof recipe以遞歸方式使用getsizeof()來查找容器及其所有內容大小的示例。](http:// code .activestate.com/recipes/577504 /) –
感謝您的回答。現在,我試圖添加一個處理程序來計算用戶定義的類的內存使用情況。 – crandrades