How do I determine the size of an object in Python?

前端 未结 13 1467
半阙折子戏
半阙折子戏 2020-11-21 21:53

I want to know how to get size of objects like a string, integer, etc. in Python.

Related question: How many bytes per element are there in a Python list (tuple)?

13条回答
  •  孤独总比滥情好
    2020-11-21 22:54

    The Pympler package's asizeof module can do this.

    Use as follows:

    from pympler import asizeof
    asizeof.asizeof(my_object)
    

    Unlike sys.getsizeof, it works for your self-created objects. It even works with numpy.

    >>> asizeof.asizeof(tuple('bcd'))
    200
    >>> asizeof.asizeof({'foo': 'bar', 'baz': 'bar'})
    400
    >>> asizeof.asizeof({})
    280
    >>> asizeof.asizeof({'foo':'bar'})
    360
    >>> asizeof.asizeof('foo')
    40
    >>> asizeof.asizeof(Bar())
    352
    >>> asizeof.asizeof(Bar().__dict__)
    280
    >>> A = rand(10)
    >>> B = rand(10000)
    >>> asizeof.asizeof(A)
    176
    >>> asizeof.asizeof(B)
    80096
    

    As mentioned,

    The (byte)code size of objects like classes, functions, methods, modules, etc. can be included by setting option code=True.

    And if you need other view on live data, Pympler's

    module muppy is used for on-line monitoring of a Python application and module Class Tracker provides off-line analysis of the lifetime of selected Python objects.

提交回复
热议问题