How can I profile a multithreaded program in Python?

I am essentially developing a multi-threaded module in Python, and I would like to know where it spends its time. cProfile only seems to profile the main thread. Is there a way to profile all the threads involved in the calculation?

+44
python multithreading profiling
Mar 17 '09 at 8:45
source share
5 answers

See yappi (another Python profiler).

+27
Nov 01 '09 at 22:09
source share

Instead of running a single cProfile , you can run a separate instance of cProfile in each thread, and then combine the statistics. Stats.add() does this automatically.

+14
Mar 17 '09 at 9:21
source share

If you do the extra work, you can write your own profiling class that implements profile(self, frame, event, arg) . It is called whenever a function is called, and you can pretty easily set up a structure to collect statistics.

Then you can use threading.setprofile to register this function in each thread. When a function is called, you can use threading.currentThread() to see what it works on. More information (and a ready-to-use recipe) can be found here:

http://code.activestate.com/recipes/465831/

http://docs.python.org/library/threading.html#threading.setprofile

+4
Mar 17 '09 at 13:22
source share

Given that the main functions of your different threads are different, you can use the very useful profile_func() decorator from here .

+1
Mar 17 '09 at 21:19
source share

I don’t know any profiling application that supports such a thing for python, but you could write a Trace class that writes log files, where you put information about when the operation started and when it ended, and how much time, which it consumed.

This is a simple and quick solution to your problem.

0
Mar 17 '09 at 9:16
source share



All Articles