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

posted on   荣锋亮  阅读(1578)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2018-03-22 lapis docker 运行说明
2017-03-22 saas 系统租户个性化域名&&租户绑定自己域名的解决方案

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示