Add tool for profiling (#364)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Florimond Manca · committed by Seth Michael Larson · parent 08355c6 · Browse files · 13 files·+187 added−3 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+187 added−3 removed
- other:+187 added−3 removed
Provenance
- Commit
e1da6b9- Tree
acbd99a- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
Seth Michael Larson <sethmichaellarson@gmail.com>- Parent
08355c6
13 files changed+187 added−3 removed
added:tools/httpxprof/httpxprof/scripts/__init__.py
added:tools/httpxprof/httpxprof/scripts/async.py+15 added
1+import asyncio2+3+import tqdm4+5+import httpx6+from httpxprof.config import SERVER_URL7+8+9+async def main() -> None:10+ async with httpx.AsyncClient() as client:11+ for _ in tqdm.tqdm(range(1000)):12+ await client.get(SERVER_URL)13+14+15+asyncio.run(main())added:tools/httpxprof/httpxprof/scripts/sync.py+13 added
1+import tqdm2+3+import httpx4+from httpxprof.config import SERVER_URL5+6+7+def main() -> None:8+ with httpx.Client() as client:9+ for _ in tqdm.tqdm(range(1000)):10+ client.get(SERVER_URL)11+12+13+main()added:tools/httpxprof/httpxprof/__init__.py
added:tools/httpxprof/httpxprof/__main__.py+5 added
1+import sys2+3+from .cli import cli4+5+sys.exit(cli())added:tools/httpxprof/httpxprof/config.py+9 added
1+import pathlib2+3+SERVER_HOST = "127.0.0.1"4+SERVER_PORT = 81235+SERVER_URL = f"http://{SERVER_HOST}:{SERVER_PORT}"6+7+OUTPUT_DIR = pathlib.Path(__file__).parent / "out"8+SCRIPTS_DIR = pathlib.Path(__file__).parent / "scripts"9+assert SCRIPTS_DIR.exists(), SCRIPTS_DIRadded:tools/httpxprof/httpxprof/main.py+45 added
1+import os2+import subprocess3+4+import click5+6+from .config import OUTPUT_DIR, SCRIPTS_DIR, SERVER_HOST, SERVER_PORT7+from .utils import server8+9+SCRIPTS = [10+ filename.rstrip(".py")11+ for filename in os.listdir(SCRIPTS_DIR)12+ if filename != "__init__.py"13+]14+15+16+@click.group()17+def cli() -> None:18+ pass19+20+21+@cli.command()22+@click.argument("script", type=click.Choice(SCRIPTS))23+def run(script: str) -> None:24+ os.makedirs(OUTPUT_DIR, exist_ok=True)25+26+ out = str(OUTPUT_DIR / f"{script}.prof")27+ target = str(SCRIPTS_DIR / f"{script}.py")28+29+ args = ["python", "-m", "cProfile", "-o", out, target]30+31+ with server(host=SERVER_HOST, port=SERVER_PORT):32+ subprocess.run(args)33+34+35+@cli.command()36+@click.argument("script", type=click.Choice(SCRIPTS))37+def view(script: str) -> None:38+ args = ["snakeviz", str(OUTPUT_DIR / f"{script}.prof")]39+ subprocess.run(args)40+41+42+if __name__ == "__main__":43+ import sys44+45+ sys.exit(cli())added:tools/httpxprof/httpxprof/utils.py+49 added
1+import contextlib2+import multiprocessing3+import time4+import typing5+6+import uvicorn7+8+9+async def app(scope: dict, receive: typing.Callable, send: typing.Callable) -> None:10+ assert scope["type"] == "http"11+ res = b"Hello, world"12+ await send(13+ {14+ "type": "http.response.start",15+ "status": 200,16+ "headers": [17+ [b"content-type", b"text/plain"],18+ [b"content-length", b"%d" % len(res)],19+ ],20+ }21+ )22+ await send({"type": "http.response.body", "body": res})23+24+25+@contextlib.contextmanager26+def server(host: str, port: int) -> typing.Iterator[None]:27+ config = uvicorn.Config(28+ app=app,29+ host=host,30+ port=port,31+ lifespan="off",32+ loop="asyncio",33+ log_level="warning",34+ )35+ server = uvicorn.Server(config)36+37+ proc = multiprocessing.Process(target=server.run)38+ proc.start()39+40+ # Wait a bit for the uvicorn server process to be ready to accept connections.41+ time.sleep(0.2)42+ print(f"Server started at {host}:{port}.")43+44+ try:45+ yield46+ finally:47+ print("Stopping server...")48+ proc.terminate()49+ proc.join()added:tools/httpxprof/.gitignore+1 added
1+out/added:tools/httpxprof/README.md+27 added
1+# httpxprof2+3+A tool for profiling [HTTPX](https://github.com/encode/httpx) using cProfile and [SnakeViz](https://jiffyclub.github.io/snakeviz/).4+5+## Usage6+7+```bash8+# Run one of the scripts:9+httpxprof run async10+11+# View results:12+httpxprof view async13+```14+15+You can ask for `--help` on `httpxprof` and any of the subcommands.16+17+## Installation18+19+```bash20+# From the HTTPX project root directory:21+pip install -e tools/httpxprof22+23+# From this directory:24+pip install -e .25+```26+27+`httpxprof` assumes it can `import httpx`, so you need to have HTTPX installed (either from local or PyPI).added:tools/httpxprof/setup.py+20 added
1+import typing2+from pathlib import Path3+4+from setuptools import setup5+6+7+def get_packages(package: str) -> typing.List[str]:8+ return [str(path.parent) for path in Path(package).glob("**/__init__.py")]9+10+11+setup(12+ name="httpxprof",13+ version="0.1",14+ packages=get_packages("httpxprof"),15+ install_requires=["click", "snakeviz", "uvicorn", "tqdm"],16+ entry_points="""17+ [console_scripts]18+ httpxprof=httpxprof.main:cli19+ """,20+)modified:noxfile.py+1 added-1 removed
1 import nox2 3 nox.options.stop_on_first_error = True4 5-source_files = ("httpx", "tests", "setup.py", "noxfile.py")5+source_files = ("httpx", "tools", "tests", "setup.py", "noxfile.py")6 7 8 @nox.session(reuse_venv=True)9 def lint(session):32 unmodified linesmodified:setup.cfg+2 added-2 removed
8 unmodified lines9 [tool:isort]10 combine_as_imports = True11 force_grid_wrap = 012 include_trailing_comma = True13-known_first_party = httpx,tests14-known_third_party = brotli,certifi,chardet,cryptography,h11,h2,hstspreload,nox,pytest,requests,rfc3986,setuptools,trio,trustme,uvicorn13+known_first_party = httpx,httpxprof,tests14+known_third_party = brotli,certifi,chardet,click,cryptography,h11,h2,hstspreload,nox,pytest,requests,rfc3986,setuptools,tqdm,trio,trustme,uvicorn15 line_length = 8816 multi_line_output = 317 18 [tool:pytest]3 unmodified lines