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)?
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.