使用py-spy 分析python 应用的性能问题

py-spy 是使用rust 开发的基于采样的profiler ,可以方便的用来分析python 应用的性能,同时还能生成火焰图(很强大)
以下是fastapi 的学习以及一个基于py-spy 的火焰图生成

fastapi

  • 环境准备

    推荐基于venv 安装运行

 
pip install fastapi
pip install uvicorn
  • 简单代码
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
    return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}
  • 运行
uvicorn main:app

py-spy 安装

官方提供了基于pip 的以及构建好的二进制文件(跨平台。。。)
我直接使用了预编译好的二进制文件

使用

  • py-spy的命令
 
py-spy 0.3.3
Sampling profiler for Python programs 
USAGE:
    py-spy <SUBCOMMAND>
OPTIONS:
    -h, --help Prints help information
    -V, --version Prints version information
SUBCOMMANDS:
    record Records stack trace information to a flamegraph, speedscope or raw file
    top Displays a top like view of functions consuming CPU
    dump Dumps stack traces for a target program to stdout
    help Prints this message or the help of the given subcommand(s)
 
 
  • 火焰图生成

    通过pid 方式,需要先获取运行的fastapi 的pid 通过ps -ef |grep python 即可

给系统一些压力
ab -n 10000 -c 100 <a href="http://127.0.0.1:8000/items/5?q=somequery">http://127.0.0.1:8000/items/5?q=somequery</a>
火焰图生成
sudo py-spy record -o profile.svg -p 24609

效果

  • top 效果

 

  

说明

py-spy 是一个比较强大,而且灵活的火焰图工具,是我们性能优化的一个不错的工具

参考资料

https://github.com/tiangolo/fastapi
https://github.com/benfred/py-spy

原文地址:https://www.cnblogs.com/rongfengliang/p/12548544.html