Skip to content Skip to sidebar Skip to footer

How Can I Profile Class Methods Of My Python App?

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

Solution 1:

Take a look at Yappi

To profile a piece of code simply use:

import yappi
[...]
yapp.start()
some_function_that_needs_profiling()
yappi.print_stats()

Solution 2:

The profile function is a decorator itself, and like most decorators, they need to be applied to functions only.

Luckily, class methods are basically functions that are bound to an instance when an instance is created. Thus, you can apply your decorator to any class method by putting it in the class definition by the methods themselves:

classmyApp(object):
    @do_profile(DO_PROFILE)deffoo_method(self, arg1):
        pass    @do_profile(DO_PROFILE)defbar_method(self, arg2):
        pass

If you use python 2.6 or up, you can also create a class decorator and apply the profile decorator to all methods on any given class. You'd apply it by placing the decorator right before the class definition:

@do_profile_all_methods(DO_PROFILE)classmyApp(object):
    deffoo_method(self):
        pass

Such a decorator could look something like this:

import types

defdo_profile_all_methods(cond):
    ifnot cond:
        returnlambda c: c # Do nothing with the class; the 'null' decoratordefprofile_all_methods(klass):
        for name, attr in klass.__dict__.items():
            ifisinstance(attr, types.UnboundMethodType):
                klass[name] = profile(attr)
        return klass
    return profile_all_methods

This decorator only applies the profile wrapper to direct methods, not any inherited from the base class.

Post a Comment for "How Can I Profile Class Methods Of My Python App?"