【发布时间】:2011-05-28 09:52:16
【问题描述】:
我想使用 cProfile 在 Python 中分析函数的方法。我尝试了以下方法:
import cProfile as profile
# Inside the class method...
profile.run("self.myMethod()", "output_file")
但它不起作用。如何使用“run”调用 self.method?
【问题讨论】:
我想使用 cProfile 在 Python 中分析函数的方法。我尝试了以下方法:
import cProfile as profile
# Inside the class method...
profile.run("self.myMethod()", "output_file")
但它不起作用。如何使用“run”调用 self.method?
【问题讨论】:
import cProfile
p = cProfile.Profile()
p.runcall(self.myMethod)
p.print_stats()
Profile 类记录在 here。
【讨论】:
如果您的配置文件下的函数返回值,您需要稍微更改@katrielalex 的出色答案:
... profile.runctx('val = self.baz()', globals(), locals())
... print locals()['val']
【讨论】:
编辑:抱歉,没有意识到配置文件调用是在类方法中。
run 只是尝试exec 你传递给它的字符串。如果self 未绑定到您正在使用的分析器范围内的任何内容,则不能在run 中使用它!使用runctx方法将调用范围内的局部和全局变量传入profiler:
>>> 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 是占用时间的内容。
【讨论】:
cProfile.runctx() 传递给当前的globals() 和locals() 允许对任意方法进行分析——与宣传的完全一样。谢谢你,katrielalex。
我不建议分析单个例程,因为这意味着提前知道那里存在问题。
性能问题的一个基本方面是它们是偷偷摸摸的。 它们不在您认为的位置,因为如果它们在,您早就解决了。
最好以真实的工作负载运行整个程序,让分析技术告诉您问题出在哪里。
Here's an example 分析发现问题所在,但不是预期的问题。
【讨论】:
使用 profilehooks 装饰器
【讨论】:
cProfile.runctx('self.myMethod()', globals(), locals(), output_file),正如katrielalex 建议的那样应该 是accepted answer。
profile 装饰器并将其应用到特定回调中,您可以仅在单击按钮时测试该回调。