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

前端 未结 13 1735
半阙折子戏
半阙折子戏 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:41

    Just use the sys.getsizeof function defined in the sys module.

    sys.getsizeof(object[, default]):

    Return the size of an object in bytes. The object can be any type of object. All built-in objects will return correct results, but this does not have to hold true for third-party extensions as it is implementation specific.

    Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.

    The default argument allows to define a value which will be returned if the object type does not provide means to retrieve the size and would cause a TypeError.

    getsizeof calls the object’s __sizeof__ method and adds an additional garbage collector overhead if the object is managed by the garbage collector.

    See recursive sizeof recipe for an example of using getsizeof() recursively to find the size of containers and all their contents.

    Usage example, in python 3.0:

    >>> import sys
    >>> x = 2
    >>> sys.getsizeof(x)
    24
    >>> sys.getsizeof(sys.getsizeof)
    32
    >>> sys.getsizeof('this')
    38
    >>> sys.getsizeof('this also')
    48
    

    If you are in python < 2.6 and don't have sys.getsizeof you can use this extensive module instead. Never used it though.

提交回复
热议问题