I want to know the memory usage of my Python application and specifically want to know what code blocks/portions or objects are consuming most memory. Google search shows a commercial one is Python Memory Validator (Windows only).
And open source ones are PySizer and Heapy.
I haven't tried anyone, so I wanted to know which one is the best considering:
Gives most details.
I have to do least or no changes to my code.
Heapy is quite simple to use. At some point in your code, you have to write the following:
This gives you some output like this:
You can also find out from where objects are referenced and get statistics about that, but somehow the docs on that are a bit sparse.
There is a graphical browser as well, written in Tk.
I'm developing a memory profiler for Python called memprof:
http://jmdana.github.io/memprof/
It allows you to log and plot the memory usage of your variables during the execution of the decorated methods. You just have to import the library using:
And decorate your method using:
This is an example on how the plots look like:
The project is hosted in GitHub:
https://github.com/jmdana/memprof
Consider the objgraph library (see http://www.lshift.net/blog/2008/11/14/tracing-python-memory-leaks for an example use case).
I found meliae to be much more functional than Heapy or PySizer. If you happen to be running a wsgi webapp, then Dozer is a nice middleware wrapper of Dowser
I recommend Dowser. It is very easy to setup, and you need zero changes to your code. You can view counts of objects of each type through time, view list of live objects, view references to live objects, all from the simple web interface.
You import memdebug, and call memdebug.start. That's all.
I haven't tried PySizer or Heapy. I would appreciate others' reviews.
UPDATE
The above code is for
CherryPy 2.X
,CherryPy 3.X
theserver.quickstart
method has been removed andengine.start
does not take theblocking
flag. So if you are usingCherryPy 3.X
Since nobody has mentioned it I'll point to my module memory_profiler which is capable of printing line-by-line report of memory usage and works on Unix and Windows (needs psutil on this last one). Output is not very detailed but the goal is to give you an overview of where the code is consuming more memory and not a exhaustive analysis on allocated objects.
After decorating your function with
@profile
and running your code with the-m memory_profiler
flag it will print a line-by-line report like this: