使用cProfile在Python中分析类的方法?

34 python profiler cprofile

我想使用cProfile在Python中分析函数的方法.我尝试了以下方法:

import cProfile as profile

# Inside the class method...
profile.run("self.myMethod()", "output_file")
Run Code Online (Sandbox Code Playgroud)

但它不起作用.如何用"run"调用self.method?

Kat*_*iel 48

编辑:对不起,没有意识到配置文件调用是类方法.

run只是尝试exec传递它的字符串.如果self没有绑定到您正在使用的探查器范围内的任何内容,则无法使用它run!使用该runctx方法将调用范围内的本地和全局变量传递给分析器:

>>> import time
>>> import cProfile as profile
>>> class Foo(object):
...     def bar(self):
...             profile.runctx('self.baz()', globals(), locals())
...
...     def baz(self):
...             time.sleep(1)
...             print 'slept'
...             time.sleep(2)
...
>>> foo = Foo()
>>> foo.bar()
slept
         5 function calls in 2.999 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    2.999    2.999 <stdin>:5(baz)
        1    0.000    0.000    2.999    2.999 <string>:1(<module>)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        2    2.999    1.499    2.999    1.499 {time.sleep}
Run Code Online (Sandbox Code Playgroud)

注意最后一行:time.sleep是占用时间的.

  • 如何让剖析器"深入挖掘",即不只是说所有时间都花在模块的某个功能上,而是递归地钻研到该模块中调用的函数? (2认同)
  • **才华横溢!** 传递 `cProfile.runctx()` 当前的 `globals()` 和 `locals()` 允许对任意方法进行分析——正如宣传的那样。谢谢你,[katrielalex](/sf/users/27927791/)。 (2认同)

Fal*_*rri 25

使用profilehooks装饰器

http://pypi.python.org/pypi/profilehooks

  • **否.**不要安装重量级依赖项.只需调用`cProfile.runctx('self.myMethod()',globals(),locals(),output_file)`,如[katrielalex](/sf/users/27927791/)建议_should_一直是[接受的答案](/sf/answers/314480771/). (8认同)

Jul*_*nze 5

  import cProfile
  p = cProfile.Profile()
  p.runcall(self.myMethod)
  p.print_stats()
Run Code Online (Sandbox Code Playgroud)

该类Profile记录在此处