How can I check the memory usage of objects in iPython?

前端 未结 4 468
萌比男神i
萌比男神i 2020-12-01 04:21

I am using iPython to run my code. I wonder if there is any module or command which would allow me to check the memory usage of an object. For instance:

In [         


        
4条回答
  •  悲哀的现实
    2020-12-01 04:46

    UPDATE: Here is another, maybe more thorough recipe for estimating the size of a python object.

    Here is a thread addressing a similar question

    The solution proposed is to write your own... using some estimates of the known size of primitives, python's object overhead, and the sizes of built in container types.

    Since the code is not that long, here is a direct copy of it:

    def sizeof(obj):
        """APPROXIMATE memory taken by some Python objects in 
        the current 32-bit CPython implementation.
    
        Excludes the space used by items in containers; does not
        take into account overhead of memory allocation from the
        operating system, or over-allocation by lists and dicts.
        """
        T = type(obj)
        if T is int:
            kind = "fixed"
            container = False
            size = 4
        elif T is list or T is tuple:
            kind = "variable"
            container = True
            size = 4*len(obj)
        elif T is dict:
            kind = "variable"
            container = True
            size = 144
            if len(obj) > 8:
                size += 12*(len(obj)-8)
        elif T is str:
            kind = "variable"
            container = False
            size = len(obj) + 1
        else:
            raise TypeError("don't know about this kind of object")
        if kind == "fixed":
            overhead = 8
        else: # "variable"
            overhead = 12
        if container:
            garbage_collector = 8
        else:
            garbage_collector = 0
        malloc = 8 # in most cases
        size = size + overhead + garbage_collector + malloc
        # Round to nearest multiple of 8 bytes
        x = size % 8
        if x != 0:
            size += 8-x
            size = (size + 8)
        return size
    

提交回复
热议问题