#!/usr/bin/env python3 """Timing benchmarks for Chapter 8 (From Python to SQL) on Django 6.1.3. Measures: 1. Exact apples-to-apples breakdown across five query shapes on `desk/`: (a) Python QuerySet build + SQLCompiler.as_sql() compilation (`compile_us`), (b) full build + compile + SQLite cursor execution + row fetch (`total_us`), and (c) raw SQLite cursor execution on the precompiled SQL (`sqlite_us`), all over identical `values_list("id", flat=True)` queries. 2. Scaling of Cartesian join fan-out (Count(..., distinct=True) across two reverse relations) vs. correlated Subquery counts as each of 20 stories gains N=5, 10, 20, 30 beats and N=5, 10, 20, 30 corrections (N*N vs 2*N). """ from __future__ import annotations import statistics import sys import time from datetime import datetime, timezone from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) from harness import Recorder, boot_desk UTC = timezone.utc def bench_us(fn, *, iters: int, trials: int = 7) -> float: fn() # warm up caches and imports samples: list[float] = [] for _ in range(trials): t0 = time.perf_counter() for _ in range(iters): fn() samples.append((time.perf_counter() - t0) * 1e6 / iters) return statistics.median(samples) def bench_ms(fn, *, iters: int, trials: int = 7) -> float: fn() samples: list[float] = [] for _ in range(trials): t0 = time.perf_counter() for _ in range(iters): fn() samples.append((time.perf_counter() - t0) * 1e3 / iters) return statistics.median(samples) def main() -> None: boot_desk() from django.db import connection from django.db.models import Count, Exists, F, IntegerField, OuterRef, Subquery, Window from django.db.models.functions import RowNumber from newsroom.models import Beat, Correction, Desk, Edition, Reporter, Story, StoryBeat rec = Recorder("ch08-bench") # Part 1: Exact apples-to-apples Python compile vs full execution vs raw SQLite shapes = [ ( "simple_filter", lambda: Story.objects.filter(status=Story.Status.PUBLISHED).values_list( "id", flat=True ), ), ( "two_fk_joins", lambda: Story.objects.filter( desk__slug="metro", reporter__name="Ada" ).values_list("id", flat=True), ), ( "m2m_chained_2_aliases", lambda: Story.objects.filter(story_beats__primary=True) .filter(story_beats__beat__slug="budget") .values_list("id", flat=True), ), ( "correlated_exists", lambda: Story.objects.annotate( has_corr=Exists(Correction.objects.filter(story=OuterRef("pk"))) ) .filter(has_corr=True) .values_list("id", flat=True), ), ( "window_qualify", lambda: Story.objects.annotate( desk_rank=Window( expression=RowNumber(), partition_by=[F("desk_id")], order_by=[F("priority").asc(), F("id").asc()], ) ) .filter(desk_rank=1) .values_list("id", flat=True), ), ] with rec.block("1. Python Query+as_sql() vs total execution vs raw SQLite (7 trials, us/query)"): rec.emit( f"{'shape':<24} {'compile_us':>10} {'sqlite_us':>10} {'total_us':>10} {'compile_pct':>12} {'sql_chars':>10}" ) for name, factory in shapes: sample_sql, sample_params = factory().query.sql_with_params() def run_raw_sqlite(sql=sample_sql, params=sample_params): with connection.cursor() as cur: cur.execute(sql, params) return cur.fetchall() comp_us = bench_us( lambda f=factory: f().query.sql_with_params(), iters=1200, trials=7, ) sqlite_us = bench_us(run_raw_sqlite, iters=2000, trials=7) total_us = bench_us(lambda f=factory: list(f()), iters=800, trials=7) pct = (comp_us / total_us) * 100.0 if total_us > 0 else 0.0 rec.emit( f"{name:<24} {comp_us:10.1f} {sqlite_us:10.1f} {total_us:10.1f} {pct:11.1f}% {len(sample_sql):10d}" ) # Part 2: Join fan-out scaling (Count distinct vs correlated Subquery) with rec.block("2. Join fan-out scaling: 20 stories x (N beats * N corrections), 7 trials (ms)"): rec.emit( f"{'N_each':>6} {'joined_rows':>12} {'distinct_ms':>12} {'subquery_ms':>12} {'speedup':>9}" ) metro = Desk.objects.get(slug="metro") ada = Reporter.objects.get(name="Ada") ed = Edition.objects.get(slug="2026-11-25") for n_each in (5, 10, 20, 30): StoryBeat.objects.all().delete() Correction.objects.all().delete() Story.objects.all().delete() Beat.objects.all().delete() beats = Beat.objects.bulk_create( [Beat(name=f"Beat {i}", slug=f"beat-{i}") for i in range(n_each)] ) stories = Story.objects.bulk_create( [ Story( headline=f"Bench Story {s}", slug=f"bench-story-{s}", body="Body text.", priority=(s % 3) + 1, status=Story.Status.PUBLISHED, published_at=datetime(2026, 11, 25, 10, 0, tzinfo=UTC), desk=metro, reporter=ada, edition=ed, ) for s in range(20) ] ) StoryBeat.objects.bulk_create( [ StoryBeat(story=st, beat=bt, primary=(idx == 0), position=idx + 1) for st in stories for idx, bt in enumerate(beats) ] ) Correction.objects.bulk_create( [ Correction( story=st, note=f"Note {c}", issued_at=datetime(2026, 11, 25, 11, c % 60, tzinfo=UTC), ) for st in stories for c in range(n_each) ] ) def run_distinct(): return list( Story.objects.annotate( n_corr=Count("corrections", distinct=True), n_beats=Count("beats", distinct=True), ) .order_by("id") .values_list("id", "n_corr", "n_beats") ) def run_subquery(): corr_sq = ( Correction.objects.filter(story=OuterRef("pk")) .order_by() .values("story") .annotate(c=Count("pk")) .values("c") ) beat_sq = ( StoryBeat.objects.filter(story=OuterRef("pk")) .order_by() .values("story") .annotate(c=Count("pk")) .values("c") ) return list( Story.objects.annotate( n_corr=Subquery(corr_sq, output_field=IntegerField()), n_beats=Subquery(beat_sq, output_field=IntegerField()), ) .order_by("id") .values_list("id", "n_corr", "n_beats") ) d_rows = run_distinct() s_rows = run_subquery() assert len(d_rows) == 20 and all(c == n_each and b == n_each for _, c, b in d_rows) assert d_rows == s_rows iters = 40 if n_each <= 10 else (20 if n_each == 20 else 12) d_med = bench_ms(run_distinct, iters=iters, trials=7) s_med = bench_ms(run_subquery, iters=iters, trials=7) speedup = d_med / s_med if s_med > 0 else 0.0 rec.emit( f"{n_each:6d} {20 * n_each * n_each:12d} {d_med:12.3f} {s_med:12.3f} {speedup:8.2f}x" ) rec.write() if __name__ == "__main__": main()