#!/usr/bin/env python3 """Measured timing benchmark for Chapter 1 (One request, unwrapped). Measures median wall-clock time across 7 warm runs for the naive view vs. eager EditionListView on 4 stories and 200 stories on SQLite in-memory, plus the split between view/middleware execution and TemplateResponse.render. """ from __future__ import annotations import io import platform import statistics import sys import time from datetime import date, datetime, timezone from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) from harness import Recorder, boot_desk # noqa: E402 boot_desk() import django # noqa: E402 from django.core.handlers.wsgi import WSGIRequest # noqa: E402 from django.shortcuts import get_object_or_404 # noqa: E402 from django.views.generic import ListView # noqa: E402 from newsroom.models import Correction, Desk, Edition, Reporter, Story # noqa: E402 from newsroom.views import EditionListView # noqa: E402 class NaiveEditionListView(ListView): model = Story template_name = "newsroom/edition.html" context_object_name = "stories" def get_queryset(self): self.edition = get_object_or_404(Edition, slug=self.kwargs["issue_date"]) return Story.objects.filter(edition=self.edition, status=Story.Status.PUBLISHED) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["edition"] = self.edition return context def make_environ(path: str) -> dict[str, object]: return { "REQUEST_METHOD": "GET", "SCRIPT_NAME": "", "PATH_INFO": path, "QUERY_STRING": "", "SERVER_NAME": "desk.example", "SERVER_PORT": "80", "SERVER_PROTOCOL": "HTTP/1.1", "HTTP_HOST": "desk.example", "wsgi.version": (1, 0), "wsgi.url_scheme": "http", "wsgi.input": io.BytesIO(b""), "wsgi.errors": io.StringIO(), "wsgi.multithread": False, "wsgi.multiprocess": False, "wsgi.run_once": False, } def measure(view_cls, issue_date: str, runs: int = 7) -> tuple[int, float, float, float, float]: view_fn = view_cls.as_view() # Warm templates and SQLite statement cache once and capture exact query count. req = WSGIRequest(make_environ(f"/editions/{issue_date}/")) with rec.capture_sql(log=False) as warm_sql: view_fn(req, issue_date=issue_date).render() sql_count = warm_sql.count view_ms: list[float] = [] render_ms: list[float] = [] total_ms: list[float] = [] for _ in range(runs): req = WSGIRequest(make_environ(f"/editions/{issue_date}/")) t0 = time.perf_counter() resp = view_fn(req, issue_date=issue_date) t1 = time.perf_counter() resp.render() t2 = time.perf_counter() view_ms.append((t1 - t0) * 1000.0) render_ms.append((t2 - t1) * 1000.0) total_ms.append((t2 - t0) * 1000.0) return ( sql_count, statistics.median(view_ms), statistics.median(render_ms), statistics.median(total_ms), min(total_ms), ) rec = Recorder( "ch01-bench", f"Django {django.get_version()} on Python {platform.python_version()} (SQLite in-memory): ch01-bench", ) utc = timezone.utc desks = list(Desk.objects.order_by("id")) reporters = list(Reporter.objects.order_by("id")) big_edition = Edition.objects.create( issue_date=date(2026, 11, 29), slug="2026-11-29", title="Sunday Special", status=Edition.Status.PUBLISHED, published_at=datetime(2026, 11, 29, 11, 0, tzinfo=utc), ) big_stories = Story.objects.bulk_create( [ Story( headline=f"Sunday dispatch #{i:03d}", slug=f"sunday-dispatch-{i:03d}", body=f"Full body text for Sunday dispatch number {i}.", priority=(i % 5) + 1, status=Story.Status.PUBLISHED, published_at=datetime(2026, 11, 29, 10, 0, tzinfo=utc), desk=desks[i % len(desks)], reporter=reporters[i % len(reporters)], edition=big_edition, ) for i in range(1, 201) ] ) Correction.objects.bulk_create( [ Correction( story=big_stories[i], note=f"Clarification for dispatch #{i + 1:03d}.", issued_at=datetime(2026, 11, 29, 12, 0, tzinfo=utc), ) for i in range(0, 200, 10) ] ) with rec.block("Measured request time: naive vs. eager view (median of 7 warm runs, in-memory SQLite)"): ns4, nv4, nr4, nt4, nm4 = measure(NaiveEditionListView, "2026-11-25") es4, ev4, er4, et4, em4 = measure(EditionListView, "2026-11-25") ns200, nv200, nr200, nt200, nm200 = measure(NaiveEditionListView, "2026-11-29") es200, ev200, er200, et200, em200 = measure(EditionListView, "2026-11-29") rec.emit("view stories sql view_ms render_ms total_ms least_ms") rec.emit(f"naive 4 {ns4:3d} {nv4:5.2f} {nr4:5.2f} {nt4:5.2f} {nm4:5.2f}") rec.emit(f"eager 4 {es4:3d} {ev4:5.2f} {er4:5.2f} {et4:5.2f} {em4:5.2f}") rec.emit(f"TRAP naive 200 {ns200:3d} {nv200:5.2f} {nr200:6.2f} {nt200:6.2f} {nm200:6.2f}") rec.emit(f"eager 200 {es200:3d} {ev200:5.2f} {er200:6.2f} {et200:6.2f} {em200:6.2f}") ratio_200 = nt200 / et200 if et200 > 0 else 0.0 render_share = (nr200 / nt200 * 100.0) if nt200 > 0 else 0.0 rec.emit( f"at 200 stories (zero network latency): naive is {ratio_200:.1f}x slower than eager;" f" {render_share:.1f}% of naive time spent inside TemplateResponse.render" ) rec.write()