python:如何准确的获取一个对象(比如字典)的内存占用

       python中,sys模块里面有一个getsizeof函数,其可以获取某个对象的内存占用,但是要注意的是,该函数只能获取对象本身直接占用的内存,该对象所指向的引用所占据的内存并不会被计算在内;python中,比如当对象是一个容器时,那么getsizeof函数就无法获取该容器内部所有内容的内存占用了,返回的只是容器本身的内存占用,比如字典。

       对此,官方文档给出了一种途径,即定义一个函数,通过递归的寻找容器中的所有引用并计算其内存占用,加总后返回即可,并且也给出了定义函数的源码,源码如下(直接copy官网给出的网站,由于外网访问奇慢,故copy到本博客以供即时定义调用)。

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)


       但要注意的是,该函数对于ndarray依然不work,但是幸好ndarray可以直接通过nbytes属性直接获取其内存占用大小。

参考资料:

官方文档:https://docs.python.org/3.7/library/sys.html#sys.getsizeof

代码来源:https://code.activestate.com/recipes/577504/
————————————————
版权声明:本文为CSDN博主「S_o_l_o_n」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/S_o_l_o_n/article/details/102921863

发布了296 篇原创文章 · 获赞 221 · 访问量 54万+

猜你喜欢

转载自blog.csdn.net/qq_36387683/article/details/104991940