I'd like to profile a method of a function in Python, using cProfile. I tried the following:
import cProfile as profile
# Inside the class method...
profile.run("self.myMethod()", "output_file")
But it does not work. How can I call a self.method with "run"?
If your function under profile returns value(s), you need to change the excellent answer from @katrielalex slightly:
Use the profilehooks decorator
http://pypi.python.org/pypi/profilehooks
If you want to make a cumulative profiler, meaning to run the function several times in a row and watch the sum of the results.
you can use this
cumulative_profiler
decorator:Example
profiling the function
baz
baz
ran 5 times and printed this:specifying the amount of times
EDIT: Sorry, didn't realise that the profile call was in a class method.
run
just tries toexec
the string you pass it. Ifself
isn't bound to anything in the scope of the profiler you are using, you can't use it inrun
! Use therunctx
method to pass in the local and global variables in the scope of the call to the profiler:Notice the last line:
time.sleep
is what's taking up the time.I wouldn't recommend profiling a single routine, because that implies knowing in advance there's a problem there.
A fundamental aspect of performance problems is they're sneaky. They're not where you think they are, because if they were you would have solved them already.
It's better to run the whole program with a realistic workload and let the profiling technique tell you where the problems are.
Here's an example where profiling finds the problem, and it is not where expected.