Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python profiling methods

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)

...
like image 653
tauran Avatar asked May 21 '26 19:05

tauran


2 Answers

I've had pretty good success with these decorators: http://mg.pov.lt/profilehooks/

like image 118
PaulMcG Avatar answered May 24 '26 09:05

PaulMcG


You can look at http://docs.python.org/library/profile.html

In my personal opinion cProfile is the more intuitive and quick profiling tools for python.

To profile single class you can write simple test script and run them with cProfile.

like image 26
Davide Aversa Avatar answered May 24 '26 09:05

Davide Aversa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!