我想使用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是占用时间的.
Fal*_*rri 25
使用profilehooks装饰器
http://pypi.python.org/pypi/profilehooks
import cProfile
p = cProfile.Profile()
p.runcall(self.myMethod)
p.print_stats()
Run Code Online (Sandbox Code Playgroud)
该类Profile记录在此处。