Debugging Python’s Memory Usage with Dowser

As I mentioned in my previous post, I had to hunt down a leak (which was intentional considering the functionality) somewhere in a batch import task in my Pyramid app. I’ve never played around with any memory profilers in python before, so this was a proper opportunity to see what the different options were. StackOverflow to the rescue as usual, with a handful of suggestions for Python memory profilers.

After trying a few, I ended up with Dowser. Dowser fit my use case neatly, as my application was a long running process, was console based (since it uses cherrypy to launch its own HTTP Server, it was a good thing that it didn’t conflict with any existing serv er) and I could pause it at a proper location before it consumed too much memory (a time.sleep(largevaluehere) worked nicely, thank you).

Installing Dowser was relatively pain free (a few of the other options I tried either needed custom patches, or required the process to run all the way through before giving me the information I needed).

I needed to get a few dependencies installed:

  1. pip install pil

.. which Dowser uses to generate sparkline diagrams, and cherrypy itself:

  1. easy_install cherrypy

.. and last, checking out the latest version of Dowser from SVN:

  1. svn co http://svn.aminus.net/misc/dowser dowser

I modified the example from the Stack Overflow question above a bit, and ended up with a small helper function in the application’s helper library:

  1. def launch_memory_usage_server(port = 8080):
  2.     import cherrypy
  3.     import dowser
  4.  
  5.     cherrypy.tree.mount(dowser.Root())
  6.     cherrypy.config.update({
  7.         'environment': 'embedded',
  8.         'server.socket_port': port
  9.     })
  10.    
  11.     cherrypy.engine.start()

Then doing launch_memory_usage_server() somewhere early in my code launched the HTTP interface (http://localhost:8080/) to see memory usage while the import process was running. This helped me narrow down where the issue showed up (as we were leaking MySQLdb cursors at an alarming rate), and digging deeper into the structure hinted to the underlying cause (the debug toolbar was active for a console script).

Tags: , , ,

One Response to “Debugging Python’s Memory Usage with Dowser”

  1. Guy Rozendorn Says:

    Awesome tool, VERY easy to use, helped us a lot today

    To make it even easier, we took your work, added a setup.py to it and uploaded to PyPI:
    https://github.com/Infinidat/dowser

    now you can just easy_install/pip dowser and:
    from dowser import launch_memory_usage_server
    launch_memory_usage_server()

Leave a Reply