Easy and informative: Call graphs in Python

While I was looking for different graphing modules in Python, I came across pycallgraph. This module allows you to create a graph of all the different calls that occur between the time you initiate it and when you tell it to make a graph. Not only that, but it shows you the number of times each was called, the total time the calls took, and how they all connected!

Running this on an entire script, much less a large app, would create a huge unreadable mess that would have value only in making an awesome poster. However, showing the calls and time taken for a single function, or part of a function, may serve well in pointing out where to look in speeding up your application. Now you can make a diagram of all the connections in your bottleneck code, colored to emphasize what took the longest (hotter colors took longest).

To use pycallgraph, you need to:

  • 1
    sudo easy_install pycallgraph
  • 1
    sudo apt-get install python-pygraphviz

This will get all the dependencies. Then in your code, right above where you want to start tracking, add:

import pycallgraph
pycallgraph.start_trace()

Then right after where you want to stop tracking, add:

pycallgraph.make_dot_graph('test.png')

You can pass various options to these, but just these three lines will produce an image file, test.png, in the folder where you ran the script. I added these lines around the main function of the follow-largest-directories script I blogged about recently, right after all the option parsing stuff. Here was the result:

Post to Twitter Post to Delicious Post to Digg Post to Reddit

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

This entry was posted in Programming and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>