使用 cProfile 分析 Python 中类的方法?
我想使用 cProfile 来分析 Python 中函数的方法。我尝试了以下方法:
import cProfile as profile
# Inside the class method...
profile.run("self.myMethod()", "output_file")
但它不起作用。如何使用“run”调用 self.method?
I'd like to profile a method of a function in Python, using cProfile. I tried the following:
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"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
run
只是尝试exec
您传递给它的字符串。如果self
未绑定到您正在使用的探查器范围内的任何内容,则您无法在run
中使用它!使用runctx
方法传入调用探查器范围内的本地和全局变量:请注意最后一行:
time.sleep
是占用时间的内容。run
just tries toexec
the string you pass it. Ifself
isn't bound to anything in the scope of the profiler you are using, you can't use it inrun
! Use therunctx
method to pass in the local and global variables in the scope of the call to the profiler:Notice the last line:
time.sleep
is what's taking up the time.使用 profilehooks 装饰器
http://pypi.python.org/pypi/profilehooks
Use the profilehooks decorator
http://pypi.python.org/pypi/profilehooks
Profile
类记录在此处 。The
Profile
class is documented here.如果您的配置文件下的函数返回值,您需要稍微更改@katrielalex 的优秀答案:
If your function under profile returns value(s), you need to change the excellent answer from @katrielalex slightly:
我不建议对单个例程进行分析,因为这意味着提前知道那里存在问题。
性能问题的一个基本方面是它们是偷偷摸摸的。
它们并不在你想象的地方,因为如果它们在,你早就解决了它们。
最好以实际工作负载运行整个程序,并让分析技术告诉您问题出在哪里。
这是一个示例,其中分析发现了问题,并且它不是预期的地方。
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 example where profiling finds the problem, and it is not where expected.