Take the 2-minute tour ×

How do I call cProfile from within a function, using it to call and profile another function?

I have a function start(), which is called from my webpage (using Django). In this function I place the cProfile call:


This gives me the error "Name my_function is not defined". However, the function is called no problem if I just do a normal function call: my_function()

Everything says to execute the "main" function using cProfile, but I don't really have a single main function or an obvious way to run my program except from the webpage.

share|improve this question

1 Answer 1

up vote 4 down vote accepted

You need runctx instead of run.

You can pass globals and locals to the cProfile.runctx call, like this:

cProfile.runctx('my_function()', globals=globals(), locals=locals())
share|improve this answer
Works like a charm, thanks! –  user984003 Sep 4 '12 at 13:36

Your Answer


