有没有可以分析Python代码的工具?
我正在寻找一个工具来分析我的 python 脚本。例如
- 哪部分代码花费的时间最多,
- 哪部分代码消耗太多内存
- 等等......
有类似的东西吗?
I am looking for a tool to analyze my python script. For example
- which part of the code takes the most time
- which part of the code consumes too much memory
- and so on...
Is there something like that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Python 有一个内置分析器
有 Python 的各种内存分析器
Python has a built-in profiler
There are various memory profilers for Python
查看cProfile。这是一个使用示例:
一个好的内存分析器,如 Sven Marnach,Heapy
Take a look at cProfile. Here's a usage example:
A good memory profiler, as mentioned in the post linked to by Sven Marnach, is Heapy
我经常使用 Ipython 来分析我的代码。像这样使用神奇命令“%run”执行脚本(在 ipython 提示符内):
在 Python 分析器模块的控制下运行程序。
您甚至可以使用“%prun”魔法分析语句(例如函数调用):
%prun 的优点在于它在当前会话的上下文中执行语句(即您可以使用您之前定义的变量以及当前命名空间中的任何其他内容)。
如果您想获取每行分析信息,我发现 line_profiler 模块非常方便。它有点旧,但它完成了工作......正如 Robert Kern 编码的内容所期望的那样;-)。
I frequently use Ipython to profile my code. Executing a script with the magic command "%run" like this (inside an ipython prompt):
runs the program under the control of the Python profiler module.
You can even profile statements (e.g. a function call) with the "%prun" magic:
What is nice about %prun, is that it executes the statement in the context of your current session (i.e. you can use variables you previously defined and anything else in your current namespace).
If you want to get per-line profiling information, I found the line_profiler module to be quite handy. It is a bit old, but it does the job... as expected from something coded by Robert Kern ;-).