使用Cprofile分析Python中类的方法?
题
我想使用CPROFILE介绍Python中功能的方法。我尝试了以下内容:
import cProfile as profile
# Inside the class method...
profile.run("self.myMethod()", "output_file")
但是它行不通。我该如何称呼“ run”的self.method?
解决方案
使用profilehooks装饰师
其他提示
编辑:对不起,没有意识到个人资料电话是 在 类方法。
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}
注意最后一行: time.sleep
就是耗时的时间。
我不建议分析单个例程,因为这意味着事先知道那里存在问题。
性能问题的一个基本方面是它们偷偷摸摸。它们不是您认为它们的位置,因为如果它们是您已经解决的。
最好用现实的工作量运行整个程序,并让分析技术告诉您问题在哪里。
这是一个例子 分析发现问题的地方,这不是预期的。
如果您的配置文件下的功能返回值,则需要稍微从@katrielalex更改出色的答案:
... profile.runctx('val = self.baz()', globals(), locals())
... print locals()['val']
不隶属于 StackOverflow