Skip to content
Myr

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

13 files+187 added−3 removed

added:tools/httpxprof/httpxprof/scripts/__init__.py
added:tools/httpxprof/httpxprof/scripts/async.py+15 added
1import asyncio23import tqdm45import httpx6from httpxprof.config import SERVER_URL789async def main() -> None:10 async with httpx.AsyncClient() as client:11 for _ in tqdm.tqdm(range(1000)):12 await client.get(SERVER_URL)131415asyncio.run(main())
added:tools/httpxprof/httpxprof/scripts/sync.py+13 added
1import tqdm23import httpx4from httpxprof.config import SERVER_URL567def main() -> None:8 with httpx.Client() as client:9 for _ in tqdm.tqdm(range(1000)):10 client.get(SERVER_URL)111213main()
added:tools/httpxprof/httpxprof/__init__.py
added:tools/httpxprof/httpxprof/__main__.py+5 added
1import sys23from .cli import cli45sys.exit(cli())
added:tools/httpxprof/httpxprof/config.py+9 added
1import pathlib23SERVER_HOST = "127.0.0.1"4SERVER_PORT = 81235SERVER_URL = f"http://{SERVER_HOST}:{SERVER_PORT}"67OUTPUT_DIR = pathlib.Path(__file__).parent / "out"8SCRIPTS_DIR = pathlib.Path(__file__).parent / "scripts"9assert SCRIPTS_DIR.exists(), SCRIPTS_DIR
added:tools/httpxprof/httpxprof/main.py+45 added
1import os2import subprocess34import click56from .config import OUTPUT_DIR, SCRIPTS_DIR, SERVER_HOST, SERVER_PORT7from .utils import server89SCRIPTS = [10 filename.rstrip(".py")11 for filename in os.listdir(SCRIPTS_DIR)12 if filename != "__init__.py"13]141516@click.group()17def cli() -> None:18 pass192021@cli.command()22@click.argument("script", type=click.Choice(SCRIPTS))23def run(script: str) -> None:24 os.makedirs(OUTPUT_DIR, exist_ok=True)2526 out = str(OUTPUT_DIR / f"{script}.prof")27 target = str(SCRIPTS_DIR / f"{script}.py")2829 args = ["python", "-m", "cProfile", "-o", out, target]3031 with server(host=SERVER_HOST, port=SERVER_PORT):32 subprocess.run(args)333435@cli.command()36@click.argument("script", type=click.Choice(SCRIPTS))37def view(script: str) -> None:38 args = ["snakeviz", str(OUTPUT_DIR / f"{script}.prof")]39 subprocess.run(args)404142if __name__ == "__main__":43 import sys4445 sys.exit(cli())
added:tools/httpxprof/httpxprof/utils.py+49 added
1import contextlib2import multiprocessing3import time4import typing56import uvicorn789async 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})232425@contextlib.contextmanager26def 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)3637 proc = multiprocessing.Process(target=server.run)38 proc.start()3940 # 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}.")4344 try:45 yield46 finally:47 print("Stopping server...")48 proc.terminate()49 proc.join()
added:tools/httpxprof/.gitignore+1 added
1out/
added:tools/httpxprof/README.md+27 added
1# httpxprof23A tool for profiling [HTTPX](https://github.com/encode/httpx) using cProfile and [SnakeViz](https://jiffyclub.github.io/snakeviz/).45## Usage67```bash8# Run one of the scripts:9httpxprof run async1011# View results:12httpxprof view async13```1415You can ask for `--help` on `httpxprof` and any of the subcommands.1617## Installation1819```bash20# From the HTTPX project root directory:21pip install -e tools/httpxprof2223# From this directory:24pip install -e .25```2627`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
1import typing2from pathlib import Path34from setuptools import setup567def get_packages(package: str) -> typing.List[str]:8 return [str(path.parent) for path in Path(package).glob("**/__init__.py")]91011setup(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
1import nox23nox.options.stop_on_first_error = True45source_files = ("httpx", "tests", "setup.py", "noxfile.py")5source_files = ("httpx", "tools", "tests", "setup.py", "noxfile.py")678@nox.session(reuse_venv=True)9def lint(session):
32 unmodified lines
modified:setup.cfg+2 added-2 removed
8 unmodified lines
9[tool:isort]10combine_as_imports = True11force_grid_wrap = 012include_trailing_comma = True13known_first_party = httpx,tests14known_third_party = brotli,certifi,chardet,cryptography,h11,h2,hstspreload,nox,pytest,requests,rfc3986,setuptools,trio,trustme,uvicorn13known_first_party = httpx,httpxprof,tests14known_third_party = brotli,certifi,chardet,click,cryptography,h11,h2,hstspreload,nox,pytest,requests,rfc3986,setuptools,tqdm,trio,trustme,uvicorn15line_length = 8816multi_line_output = 31718[tool:pytest]
3 unmodified lines