以下是几个常用的性能分析工具及其使用方法和常用命令:
1. cProfile
cProfile是Python标准库中的性能分析工具,可以用来统计函数的运行时间和调用次数。
使用方法:
在命令行中使用以下命令:
python -m cProfile my_script.py
其中,my_script.py
是你要运行的Python脚本。
常用命令:
-
-s
:指定排序方式,如-s cumulative
按累计运行时间排序。 -
-o
:将分析结果保存到文件中,如-o output.prof
。 -
-m
:限制显示的函数数量,如-m 10
只显示前10个函数。
2. line_profiler
line_profiler可以分析每行代码的执行时间。
安装:
pip install line_profiler
使用方法:
在代码中使用装饰器@profile
,然后运行你的代码。
from line_profiler import LineProfiler
profiler = LineProfiler()
profiler.add_function(my_function)