使用 cProfile 在 Python 中分析类的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4492535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
profiling a method of a class in Python using cProfile?
提问by
I'd like to profile a method of a function in Python, using cProfile. I tried the following:
我想使用 cProfile 在 Python 中分析一个函数的方法。我尝试了以下方法:
import cProfile as profile
# Inside the class method...
profile.run("self.myMethod()", "output_file")
But it does not work. How can I call a self.method with "run"?
但它不起作用。如何使用“run”调用 self.method?
采纳答案by Falmarri
回答by Katriel
EDIT: Sorry, didn't realise that the profile call was ina class method.
编辑:抱歉,没有意识到配置文件调用是在类方法中。
runjust tries to execthe string you pass it. If selfisn't bound to anything in the scope of the profiler you are using, you can't use it in run! Use the runctxmethod to pass in the local and global variables in the scope of the call to the profiler:
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}
Notice the last line: time.sleepis what's taking up the time.
注意最后一行:time.sleep是什么占用了时间。
回答by Mike Dunlavey
I wouldn't recommend profiling a single routine, because that implies knowing in advance there's a problem there.
我不建议分析单个例程,因为这意味着提前知道那里存在问题。
A fundamental aspect of performance problems is they're sneaky. They're not where you think they are, because if they were you would have solved them already.
性能问题的一个基本方面是它们是偷偷摸摸的。它们不在您认为的位置,因为如果是,您早就解决了。
It's better to run the whole program with a realistic workload and let the profiling technique tell you where the problems are.
最好以实际工作负载运行整个程序,让分析技术告诉您问题出在哪里。
Here's an examplewhere profiling finds the problem, and it is not where expected.
回答by sqqqrly
If your function under profile returns value(s), you need to change the excellent answer from @katrielalex slightly:
如果配置文件下的函数返回值,则需要稍微更改@katrielalex 的优秀答案:
... profile.runctx('val = self.baz()', globals(), locals())
... print locals()['val']

