Call Python cProfile from within a function. (Or other way to use cProfile with Django)

StackOverflow https://stackoverflow.com/questions/12248409

  •  29-06-2021
  •  | 
  •  

Question

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:

cProfile.run('my_function()')

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.

Was it helpful?

Solution

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())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top