python程序性能分析

python程序性能分析

cProfile

https://docs.python.org/3/library/profile.html
https://www.cnblogs.com/kaituorensheng/p/4453953.html

python -m cProfile [-o output_file] [-s sort_order] (-m module | myscript.py)
  1. -o 将结果输出到文件而不是stdout
  2. -s 排序状态,选择那些参数排序,常用'tottime'
  3. -m 作为一个模块而不是脚本, python3.7的cProfile中有,python3.8的Profile有

cProfile的结果很长,可以考虑使用line_profile

line_profiler

逐行的python程序性能分析,https://github.com/rkern/line_profiler
安装git clone https://github.com/rkern/line_profiler.gitpip install line_profiler

kernprof -l -v script_to_profile.py

在script_to_profile.py文件中,对想要分析的函数添加装饰器

@profile
def slow_function(a, b, c):
    ...

不加-v参数会将结果保存在script_to_profile.py.lprof文件中,使用python -m line_profiler script_to_profile.py.lprof可以查看。

memory_profiler

python程序的内存监控https://github.com/pythonprofilers/memory_profiler
安装:pip install -U memory_profiler
使用方法类似于line_profiler.

资源监控

  1. 整体监控: htop
  2. I/O操作: iotop
  3. 硬盘资源:df展示每个分区,du每个文件,-h参数human-readable
  4. 内存使用:free
  5. 打开文件:lsof
  6. 网络连接与配置: ss
  7. 网络使用: nethogs和iftop

猜你喜欢

转载自www.cnblogs.com/zi-wang/p/12359526.html