LoginSignup
1
3

More than 5 years have passed since last update.

クラスのメソッド内でプロファイルをする

Posted at

背景

http://docs.python.jp/2/library/profile.html を見て、cProfile.run() でプロファイルできるんだと思ってクラスのメソッド内で使うと NameError: name 'self' is not defined のエラーになってしまう。

import cProfile

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

    def anotherFunc(self):
        pass

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

2度はまったので3度目はまる前にメモしとく。

解決方法

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()

http://stackoverflow.com/questions/4492535/profiling-a-method-of-a-class-in-python-using-cprofile を参考にした

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3