How do I measure the memory usage of an object in python?

Posted on

Question :

How do I measure the memory usage of an object in python?

I have a python class foo that contains:

  • data (ints, floats)
  • lists (of ints, of floats, and of other objects)
  • dictionaries (of ints, of floats, of other objects)

Assuming that there are no back-references (cycles), is there an easy way to measure the total memory usage of a foo object ?

Essentially, I am looking for a recursive version of sys.getsizeof

A few of the tools I came across included: heapy, objgraph and gc, but I don’t think any of them are up to the task (I may be corrected on this)

Asked By: Ciaran

||

Answer #1:

Try Pympler, which describes itself as “A development tool to measure, monitor and analyze the memory behavior of Python objects.”

Something along the lines of

>>> import pympler
>>> print pympler.asizeof.asizeof(your_object)

has been helpful to me in the past.

See examples from the official documentation and other questions on stack overflow.

Answered By: Scott Griffiths

Answer #2:

I’m not sure if you’re trying to get the size of the type, or the actual complex object, but looking at getsizeof, the documentation points to this recipe for a robust recursive version:

http://code.activestate.com/recipes/577504/

so I’d assume there’s no ‘stock’ python call that will do it, otherwise the docs would mention it.

Answered By: Oren Mazor

Leave a Reply

Your email address will not be published.