Last active
August 18, 2021 17:21
-
-
Save tonybaloney/c6921e59cf019f3d90fd30100367fdf5 to your computer and use it in GitHub Desktop.
PyInstrument with FastAPI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from fastapi import FastAPI, Request | |
from fastapi.responses import HTMLResponse | |
from profiler import FastApiProfiler | |
app = FastAPI() | |
import .routes # NOQA | |
PROFILING = True # Put this in Settings when you're ready | |
if PROFILING: | |
@app.middleware("http") | |
async def profile_request(request: Request, call_next): | |
profile = FastApiProfiler() | |
profile.start() | |
response = await call_next(request) | |
profile.stop() | |
return HTMLResponse(profile.get_result_html()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
from pyinstrument import Profiler | |
class FastApiProfiler: | |
def __init__( | |
self, | |
interval: float = 0.0001, | |
): | |
self._profiler = Profiler(interval=interval, async_mode="enabled") | |
def start(self) -> None: | |
self._profiler.start() | |
self._begin = time.perf_counter() | |
def stop(self): | |
self._profiler.stop() | |
self._end = time.perf_counter() | |
def get_result_html(self) -> str: | |
return self._profiler.output_html() | |
def get_result_text(self, color=True) -> str: | |
return self._profiler.output_text(color=color) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment