Wednesday, January 08, 2014

Profiling a method on Python

This week I needed to do a profile session and usually on Python I just use the profile module and dump the output stats (of cProfile) in textual mode (which is usually enough to find out about the problem).

Now, this week I had to do some profiling which demanded a bit more, so, researching a bit, it seems that graphviz (http://www.graphviz.org/) can be used to plot the results of the profile session output with the help of gprof2dot (http://gprof2dot.jrfonseca.googlecode.com/git/gprof2dot.py).

So, using the code below (gist from https://gist.github.com/fabioz/8314370), it's possible to profile a function and have a graphical (.svg) output with the results of the profile (besides the usual text output, which I usually save temporarily during a profile session to compare the results from subsequent optimizations).

Hopefully the docstring explains how to use it properly (as well as its dependencies):




Note that it relies on having a .svg viewer installed (I had Inkscape: http://www.inkscape.org/ installed, so, I'm just using it, but there may be better .svg viewers around).

Happy profiling!

2 comments:

Unode said...

If you only need to view (not edit) the SVG, a webbrowser will be sufficient in most cases. If Inkscape is not around Firefox or GoogleChrome might just be enough for the task.

Anonymous said...

Better yet, we use runsnake which gives an excellent overview and a way to drilldown to details.