I would like to profile python code from an object point of view. E.g.:
foo = Foo()
profiled_foo = add_profiling(foo)
# use profiled_foo like foo
...
# later
profiled_foo.print_profile()
And I would like to get calls per method and cumulative time spent per method. I didn't find anything similar, although I think it shouldn't be too hard to write.
Does any library like that exist? Or maybe not because profiling this way would be a bad idea?
Based on Paul McGuire's answer:
import inspect
from time import sleep
from profilehooks import profile
class Foo(object):
def a(self):
sleep(0.1)
def b(self):
sleep(0.3)
def c(self):
sleep(0.5)
def add_profiling(obj):
for k in dir(obj):
attr = getattr(obj, k)
if inspect.ismethod(attr) and k != '__init__':
setattr(obj, k, profile(attr))
if __name__ == '__main__':
foo = Foo()
add_profiling(foo)
foo.a()
foo.a()
foo.b()
foo.b()
foo.a()
foo.c()
.
*** PROFILER RESULTS ***
c (oprof.py:13)
function called 1 times
3 function calls in 0.501 CPU seconds
Ordered by: cumulative time, internal time, call count
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.501 0.501 oprof.py:13(c)
1 0.501 0.501 0.501 0.501 {time.sleep}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
0 0.000 0.000 profile:0(profiler)
...