Python性能分析工具可以帮助你识别代码中的瓶颈,优化性能。以下是一些常用的Python性能分析工具及其使用方法:
cProfile
安装:Python标准库中自带,无需额外安装。
使用方法
```python
python -m cProfile my_script.py
```
常用命令:
`-s`:指定排序方式,如 `-s cumulative` 按累计运行时间排序。
`-o`:将分析结果保存到文件中,如 `-o output.prof`。
`-m`:限制显示的函数数量,如 `-m 10` 只显示前10个函数。
line_profiler
安装:使用 `pip install line_profiler` 安装。
使用方法
```python
from line_profiler import LineProfiler
profiler = LineProfiler()
profiler.add_function(my_function)
profiler.enable() 运行你的代码
...
profiler.disable()
profiler.print_stats()
```
常用命令:
使用装饰器 `@profile` 来指定需要分析的函数。
memory_profiler 

安装:使用 `pip install memory_profiler` 安装。
使用方法
```python
from memory_profiler import profile
@profile
def my_func():
你的代码
```
常用命令:
无特定命令,但使用装饰器 `@profile` 指定需要分析的函数。
objgraph 用途:
分析整个程序中对象被引用的情况,用于分析内存泄漏。
网址:[objgraph](https://mg.pov.lt/objgraph/index.html)
py-spy 用途:
允许在不重启和修改源代码的情况下,可视化正在运行的Python程序的调用栈、时间消耗等。
特点:比 `pyflame` 更好用,支持Python 3.7及以上版本。
pyflame
用途:
允许在不重启和修改源代码的情况下,用命令行对Python进程进行profile,并查看图表结果。
这些工具各有特点,你可以根据具体需求选择合适的工具进行性能分析。