Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 871
Ciaran Avatar asked Feb 16 '11 22:02

Ciaran


People also ask

How do you measure memory usage?

To open up Resource Monitor, press Windows Key + R and type resmon into the search box. Resource Monitor will tell you exactly how much RAM is being used, what is using it, and allow you to sort the list of apps using it by several different categories.

How do I check how much memory a variable is in Python?

The deep\_getsizeof() Function getsizeof() can only tell you how much memory a primitive object takes, let's take a look at a more adequate solution. The deep\_getsizeof() function drills down recursively and calculates the actual memory usage of a Python object graph.

What is __ sizeof __ in Python?

The __sizeof__() function in Python doesn't exactly tell us the size of the object. It doesn't return the size of a generator object as Python cannot tell us beforehand that how much size of a generator is. Still, in actuality, it returns the internal size for a particular object (in bytes) occupying the memory.

Which function is used to find the memory address of an object in Python?

We can get an address using the id() function. id() function gives the address of the particular object.


1 Answers

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.

like image 199
Scott Griffiths Avatar answered Oct 24 '22 09:10

Scott Griffiths