定位程序执行耗时的代码段

本文介绍了如何通过Python的性能分析工具pyinstrument来定位并优化Fast API应用程序中的性能瓶颈。首先,需要通过pip安装pyinstrument。然后,结合Fast API的示例,展示了pyinstrument在实际开发中的应用。
摘要由CSDN通过智能技术生成

Python 性能分析工具 pyinstrument

安装:pip install pyinstrument

以Fast API演示其使用

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.openapi.docs import (
    get_redoc_html,
    get_swagger_ui_html,
    get_swagger_ui_oauth2_redirect_html,
)
from fastapi.staticfiles import StaticFiles

import logging
import time
import datetime
from pyinstrument import Profiler

logger = logging.getLogger(__name__)


def create_app():
    app = FastAPI(title="test api", docs_url=None, redoc_url=None)

    # 请求前后的处理
    @app.middleware("http")
    async def response_cost_time(request: Request, call_next):
        profiler = Profiler()
        profiler.start()
        start_time = time.time()
        str_time = str(datetime.datetime.now())
        # 请求进入时间打印
        logger.info('''{str_time}=>Request url:{req_url} to start''
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值