views:

406

answers:

3

Hi,

I'm using cProfile, pstats and Gprof2dot to profile a rather long python script.

The results tell me that the most time is spent calling a method in an object I've defined. However, what I would really like is to know exactly what line number within that function is eating up the time.

Any idea's how to get this additional information?

(By the way, I'm using Python 2.6 on OSX snow leopard if that helps...)

A: 

Suppose the amount of time being "eaten up" is some number, like 40%. Then if you just interrupt the program or pause it at a random time, the probability is 40% that you will see it, precisely exposed on the call stack. Do this 10 times, and on 4 samples, +/-, you will see it.

This tells why it works. This is an example.

Mike Dunlavey
+2  A: 

cProfile does not track line numbers within a function; it only tracks the line number of where the function was defined.

cProfile attempts to duplicate the behavior of profile (which is pure Python). profile uses pstats to store the data from running, and pstats only stores line numbers for function definitions, not for individual Python statements.

If you need to figure out with finer granularity what is eating all your time, then you need to refactor your big function into several, smaller functions.

Mark Rushakoff
refactoring into small functions is not always possible - and function calls being expensive in python, this can affect speed in a significant way.
David Cournapeau
+1: breaking into smaller parts is the simplest way. Also you can wrap some blocks into locally defined temporal (for profiling) functions. This will even allow separate accounting calls to the same function from different places.
Denis Otkidach
+1  A: 

There is a line profiler in python written by Robert Kern.

David Cournapeau
This does look like what I'm looking for... however, I am unable to install on OSX Snow Leopard, since it is looking for the 10.4 SDK (which is not there on 10.6). Can't find the reference in the build script to change this either...If it helps the exact error message I get when using "sudo python setup.py install" is:Compiling with an SDK that doesn't seem to exist: /Developer/SDKs/MacOSX10.4u.sdk
Piyush Jain
I don't have this problem on my macbook (on snow leopard as well). I would advise against using sudo for installation, that's often a bad idea (it may break your system python, and sudo does not export your env variables as you would expect).I would advise you to bring this problem on the enthought-dev mailing list
David Cournapeau