In the past I've written python code with all functions in the same file, and I could profile my programs using the following code:
This is a decorator I wrote:
def do_profile(cond):
def resdec(f):
if not cond:
return f
return profile(f)
return resdec
And this is how I use it:
@do_profile(DO_PROFILE)
def my_func():
return 1
I would then invoke kernprof.py
on my script:
kernprof.py -l my_program.py
In the meantime I got more familiar with OOP and I rewrote my program into many classes and the program is now started like this:
if __name__ == "__main__":
my_app = myApp()
my_app.run()
myApp
is a class which is also communicating heavily with other classes:
class myApp():
@do_profile(DO_PROFILE)
def foo_method(self, arg1):
pass
I've added the do_profile
decorator in front of each myApp
method, but if I run kernprof.py
, the resulting .prof
file is empty
So what's the easiest way of profiling a methods of a class? I would really love to switch this on / off with a decorator and a flag.
EDIT1: I'm really interested in the easiest possible solution here. A find a decorator to be an elegant solution, but maybe things can be done easier. What I DO NOT want to do, is using stuff like cProfile's
profile profile.runctx('self.baz()', globals(), locals())
. That is not a practical solution when handling many classes and methods.