[PYTHON] Profile within a class method

background

Looking at http://docs.python.jp/2/library/profile.html, I thought that I could profile with cProfile.run () and used it in the method of the class NameError: name'self' is not I get a defined error.

import cProfile

class MyClass(object):
    def someFunc(self):
        cProfile.run("self.anotherFunc()")

    def anotherFunc(self):
        pass

if __name__ == '__main__':
    m = MyClass()
    m.someFunc()

I got stuck twice, so make a note before the third one.

Solution

Use runctx

import cProfile

class MyClass(object):
    def someFunc(self):
        cProfile.runctx("self.anotherFunc()", globals(), locals())

    def anotherFunc(self):
        pass

if __name__ == '__main__':
    m = MyClass()
    m.someFunc()

I referred to http://stackoverflow.com/questions/4492535/profiling-a-method-of-a-class-in-python-using-cprofile

Recommended Posts

Profile within a class method
Class method static method
parallelization of class method
How to use the __call__ method in a Python class
How to write a Python class
Use instance method and class method properly
Django: Import a class from a string
Dynamically declare class like a closure
Is "destructive method" a Ruby term?
[Python] Inherit a class with class variables
Hit a method of a class instance with the Python Bottle Web API