使用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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM