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''