#!/usr/bin/env python3 """Measured timing benchmarks for Chapter 3 (Handlers, middleware, and async). Measures (median of 5 trials, zero tracing instrumentation active): 1. Raw bridge primitives (microseconds per call): - plain Python function call - direct `await async_fn()` - `await sync_to_async(fn, thread_sensitive=True)()` inside one ThreadSensitiveContext - `await sync_to_async(fn, thread_sensitive=False)()` on default executor - `async with ThreadSensitiveContext(): await sync_to_async(fn)()` (fresh per-request worker thread) - `async_to_sync(async_fn)()` with no outer loop (new event loop per call) 2. Full handler request latency on zero-DB `/ping/async/` (and sync `/ping/sync/` WSGI baseline) across 7 WSGI/ASGI middleware configurations (200 requests x 5 trials = 1,000 requests each). 3. Full handler request latency on `desk/` `GET /wire/status/` (`live_wire_status`, 3 async ORM queries) across 6 WSGI/ASGI middleware configurations (100 requests x 5 trials = 500 requests each). """ from __future__ import annotations import asyncio import atexit import io import platform import statistics import sys import tempfile import time from pathlib import Path from typing import Any ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(Path(__file__).resolve().parent)) from harness import Recorder, boot_desk # noqa: E402 boot_desk(seed_data=False) import django # noqa: E402 from asgiref.sync import ThreadSensitiveContext, async_to_sync, sync_to_async # noqa: E402 from django.conf import settings # noqa: E402 from django.core.handlers.asgi import ASGIHandler # noqa: E402 from django.core.handlers.wsgi import WSGIHandler # noqa: E402 from django.core.management import call_command # noqa: E402 from django.db import connections # noqa: E402 from django.http import HttpResponse # noqa: E402 from django.test import override_settings # noqa: E402 from django.urls import path # noqa: E402 from newsroom import views as newsroom_views # noqa: E402 from seed import seed # noqa: E402 # Use a temporary file-backed SQLite DB so ASGI's ThreadSensitiveContext worker # threads share the seeded desk/ database identically with WSGI. _TMP_DIR = tempfile.TemporaryDirectory(prefix="ch03_bench_") atexit.register(_TMP_DIR.cleanup) _DB_PATH = str(Path(_TMP_DIR.name) / "desk.sqlite3") settings.DATABASES["default"]["NAME"] = _DB_PATH connections.databases["default"]["NAME"] = _DB_PATH connections["default"].settings_dict["NAME"] = _DB_PATH connections.close_all() call_command("migrate", verbosity=0, interactive=False) seed(with_editor=True) connections.close_all() atexit.register(connections.close_all) rec = Recorder( "ch03-bench", f"Django {django.get_version()} on Python {platform.python_version()}: ch03-bench", ) async def async_ping_view(request): return HttpResponse("pong", content_type="text/plain") def sync_ping_view(request): return HttpResponse("pong", content_type="text/plain") class BenchUrls: urlpatterns = [ path("ping/async/", async_ping_view), path("ping/sync/", sync_ping_view), path("wire/status/", newsroom_views.live_wire_status), ] DEFAULT_7_MW = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] DESK_8_MW = list(settings.MIDDLEWARE) COALESCED_8_MW = DEFAULT_7_MW + ["desk.middleware.TimingHeaderMiddleware"] PURE_ASYNC_MW = ["desk.middleware.AsyncAuditMiddleware"] PING_PONG_MW = [ "desk.middleware.AsyncAuditMiddleware", "desk.middleware.TimingHeaderMiddleware", "desk.middleware.AsyncAuditMiddleware", ] def make_wsgi_environ(path_info: str) -> dict[str, Any]: return { "REQUEST_METHOD": "GET", "SCRIPT_NAME": "", "PATH_INFO": path_info, "QUERY_STRING": "", "SERVER_NAME": "desk.example", "SERVER_PORT": "80", "SERVER_PROTOCOL": "HTTP/1.1", "HTTP_HOST": "desk.example", "CONTENT_LENGTH": "0", "CONTENT_TYPE": "text/plain", "wsgi.version": (1, 0), "wsgi.url_scheme": "http", "wsgi.input": io.BytesIO(b""), "wsgi.errors": io.StringIO(), "wsgi.multithread": False, "wsgi.multiprocess": True, "wsgi.run_once": False, } def make_asgi_scope(path_str: str) -> dict[str, Any]: return { "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": "GET", "scheme": "http", "path": path_str, "raw_path": path_str.encode("ascii"), "root_path": "", "query_string": b"", "headers": [(b"host", b"desk.example")], "client": ("127.0.0.1", 50000), "server": ("desk.example", 80), } def run_wsgi_batch(handler: WSGIHandler, path_info: str, n: int) -> float: def noop_start(status, headers, exc_info=None): pass t0 = time.perf_counter() for _ in range(n): resp = handler(make_wsgi_environ(path_info), noop_start) for _chunk in resp: pass resp.close() return (time.perf_counter() - t0) * 1_000_000.0 / n # microseconds / request async def run_asgi_batch(handler: ASGIHandler, path_str: str, n: int) -> float: scope = make_asgi_scope(path_str) never = asyncio.Event() async def send(_msg): pass t0 = time.perf_counter() for _ in range(n): sent_body = False async def receive(): nonlocal sent_body if not sent_body: sent_body = True return {"type": "http.request", "body": b"", "more_body": False} await never.wait() return {"type": "http.disconnect"} await handler(scope, receive, send) return (time.perf_counter() - t0) * 1_000_000.0 / n # --------------------------------------------------------------------------- # Benchmark 1: Raw bridge primitive costs (microseconds per call) # --------------------------------------------------------------------------- TRIALS = 5 def noop_sync() -> int: return 1 async def noop_async() -> int: return 1 def bench_plain(n: int = 100_000) -> float: t0 = time.perf_counter() for _ in range(n): noop_sync() return (time.perf_counter() - t0) * 1_000_000.0 / n async def bench_direct_await(n: int = 50_000) -> float: t0 = time.perf_counter() for _ in range(n): await noop_async() return (time.perf_counter() - t0) * 1_000_000.0 / n async def bench_s2a_reused_tsc(n: int = 500) -> float: wrapped = sync_to_async(noop_sync, thread_sensitive=True) async with ThreadSensitiveContext(): await wrapped() # warm worker thread t0 = time.perf_counter() for _ in range(n): await wrapped() return (time.perf_counter() - t0) * 1_000_000.0 / n async def bench_s2a_non_sensitive(n: int = 500) -> float: wrapped = sync_to_async(noop_sync, thread_sensitive=False) await wrapped() t0 = time.perf_counter() for _ in range(n): await wrapped() return (time.perf_counter() - t0) * 1_000_000.0 / n async def bench_s2a_fresh_tsc(n: int = 100) -> float: wrapped = sync_to_async(noop_sync, thread_sensitive=True) t0 = time.perf_counter() for _ in range(n): async with ThreadSensitiveContext(): await wrapped() return (time.perf_counter() - t0) * 1_000_000.0 / n def bench_a2s_no_loop(n: int = 50) -> float: wrapped = async_to_sync(noop_async) wrapped() t0 = time.perf_counter() for _ in range(n): wrapped() return (time.perf_counter() - t0) * 1_000_000.0 / n plain_us = statistics.median(bench_plain() for _ in range(TRIALS)) await_us = statistics.median(asyncio.run(bench_direct_await()) for _ in range(TRIALS)) s2a_reused_us = statistics.median(asyncio.run(bench_s2a_reused_tsc()) for _ in range(TRIALS)) s2a_nonsens_us = statistics.median(asyncio.run(bench_s2a_non_sensitive()) for _ in range(TRIALS)) s2a_fresh_us = statistics.median(asyncio.run(bench_s2a_fresh_tsc()) for _ in range(TRIALS)) a2s_noloop_us = statistics.median(bench_a2s_no_loop() for _ in range(TRIALS)) with rec.block(f"Raw bridge primitive latency (median of {TRIALS} trials, microseconds per call)"): rec.emit("operation us_per_call vs_direct_await") rows = [ ("plain Python call noop_sync()", plain_us), ("direct await noop_async()", await_us), ("sync_to_async(thread_sensitive=False) (pooled executor)", s2a_nonsens_us), ("sync_to_async(thread_sensitive=True) (reused context)", s2a_reused_us), ("fresh ThreadSensitiveContext + 1 sync_to_async (new thread)", s2a_fresh_us), ("async_to_sync() from sync (new loop + worker per call)", a2s_noloop_us), ] for label, us in rows: rec.emit(f"{label:<59s} {us:10.2f} {us / await_us:8.1f}x") # --------------------------------------------------------------------------- # Benchmark 2: Zero-DB /ping/async/ (and /ping/sync/ baseline) across 7 configs # --------------------------------------------------------------------------- PING_N = 200 PING_CONFIGS = [ ("WSGI desk/ + sync view (/ping/sync/)", "WSGI", DESK_8_MW, "/ping/sync/"), ("ASGI pure-async (AsyncAuditMW)", "ASGI", PURE_ASYNC_MW, "/ping/async/"), ("ASGI coalesced (7 built-ins + Timing bottom)", "ASGI", COALESCED_8_MW, "/ping/async/"), ("ASGI ping-pong (Async/Timing/Async)", "ASGI", PING_PONG_MW, "/ping/async/"), ("ASGI desk/ stack (Timing at #2)", "ASGI", DESK_8_MW, "/ping/async/"), ("ASGI default 7 MiddlewareMixin", "ASGI", DEFAULT_7_MW, "/ping/async/"), ("WSGI desk/ + async view (/ping/async/)", "WSGI", DESK_8_MW, "/ping/async/"), ] ping_results: list[tuple[str, float, float]] = [] for label, kind, mw_list, url_path in PING_CONFIGS: with override_settings(MIDDLEWARE=mw_list, ROOT_URLCONF=BenchUrls): if kind == "WSGI": h = WSGIHandler() run_wsgi_batch(h, url_path, 10) # warm samples = [run_wsgi_batch(h, url_path, PING_N) for _ in range(TRIALS)] else: h = ASGIHandler() asyncio.run(run_asgi_batch(h, url_path, 10)) # warm samples = [asyncio.run(run_asgi_batch(h, url_path, PING_N)) for _ in range(TRIALS)] ping_results.append((label, statistics.median(samples), min(samples))) with rec.block(f"Zero-DB handler + middleware latency ({PING_N} requests x {TRIALS} trials, microseconds per request)"): base_us = ping_results[0][1] rec.emit("configuration median_us least_us vs_wsgi_sync") for label, med_us, least_us in ping_results: rec.emit(f"{label:<44s} {med_us:9.1f} {least_us:8.1f} {med_us / base_us:6.2f}x") # --------------------------------------------------------------------------- # Benchmark 3: desk/ live_wire_status (/wire/status/, 3 async ORM queries) # --------------------------------------------------------------------------- WIRE_N = 100 WIRE_CONFIGS = [ ("ASGI pure-async (AsyncAuditMW)", "ASGI", PURE_ASYNC_MW), ("ASGI coalesced (7 built-ins + Timing bottom)", "ASGI", COALESCED_8_MW), ("ASGI ping-pong (Async/Timing/Async)", "ASGI", PING_PONG_MW), ("ASGI desk/ stack (Timing at #2)", "ASGI", DESK_8_MW), ("ASGI default 7 MiddlewareMixin", "ASGI", DEFAULT_7_MW), ("WSGI desk/ stack", "WSGI", DESK_8_MW), ] wire_results: list[tuple[str, float, float]] = [] for label, kind, mw_list in WIRE_CONFIGS: with override_settings(MIDDLEWARE=mw_list, ROOT_URLCONF=BenchUrls): if kind == "WSGI": h = WSGIHandler() run_wsgi_batch(h, "/wire/status/", 10) # warm samples = [run_wsgi_batch(h, "/wire/status/", WIRE_N) for _ in range(TRIALS)] else: h = ASGIHandler() asyncio.run(run_asgi_batch(h, "/wire/status/", 10)) # warm samples = [asyncio.run(run_asgi_batch(h, "/wire/status/", WIRE_N)) for _ in range(TRIALS)] wire_results.append((label, statistics.median(samples), min(samples))) with rec.block(f"desk/ GET /wire/status/ latency ({WIRE_N} requests x {TRIALS} trials, microseconds per request)"): base_wire = wire_results[0][1] rec.emit("configuration median_us least_us vs_pure_async") for label, med_us, least_us in wire_results: rec.emit(f"{label:<44s} {med_us:9.1f} {least_us:8.1f} {med_us / base_wire:6.2f}x") rec.write()