Just use the
sys.getsizeof function defined in the
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
Only the memory consumption directly attributed to the object is
accounted for, not the memory consumption of objects it refers to.
defaultargument 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
getsizeofcalls the object’s
__sizeof__method and adds an additional garbage collector overhead
if the object is managed by the
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.