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).
Partition of a set of 132527 objects.Total size =8301532 bytes.IndexCount%Size%Cumulative%Kind(class/ dict of class)03514427214041226214041226 str
13839729130902016344943242 tuple
253007398569418928850 dict (no owner)
Line# Mem usage Increment Line Contents==============================================3@profile45.97 MB 0.00 MB def my_func():513.61 MB 7.64 MB a =[1]*(10**6)6166.20 MB 152.59 MB b =[2]*(2*10**7)713.61 MB -152.59 MB del b
813.61 MB 0.00 MB return a
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:
Line # Mem usage Increment Line Contents
==============================================
3 @profile
4 5.97 MB 0.00 MB def my_func():
5 13.61 MB 7.64 MB a = [1] * (10 ** 6)
6 166.20 MB 152.59 MB b = [2] * (2 * 10 ** 7)
7 13.61 MB -152.59 MB del b
8 13.61 MB 0.00 MB return a
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 the server.quickstart method has been removed and engine.start does not take the blocking flag. So if you are using CherryPy 3.X
Muppy is (yet another) Memory Usage Profiler for Python. The focus of this toolset is laid on the identification of memory leaks.
Muppy tries to help developers to identity memory leaks of Python applications. It enables the tracking of memory usage during runtime and the identification of objects which are leaking. Additionally, tools are provided which allow to locate the source of not released objects.
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:
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