我想使用 cProfile 在 Python 中分析函数的方法。我尝试了以下方法:
import cProfile as profile
# Inside the class method...
profile.run("self.myMethod()", "output_file")
但它不起作用。如何使用“run”调用 self.method?
最佳答案
编辑:抱歉,没有意识到配置文件调用是在类方法中。
run
只是尝试 exec
你传递给它的字符串。如果 self
未绑定(bind)到您正在使用的分析器范围内的任何内容,则不能在 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
是什么占用了时间。
关于python - 使用 cProfile 在 Python 中分析类的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4492535/