"""Chapter 7 benchmark: 1. Iterable hydration speed & peak allocation across 500 Story rows 2. N+1 wire comparison across 24 Story rows (FETCH_ONE vs FETCH_PEERS vs select_related+prefetch_related) 3. Bulk writes vs per-row loops across 200 Correction rows Run via: .venv\\Scripts\\python.exe recordings/ch07-bench.py """ from __future__ import annotations import platform import statistics import sys import time import tracemalloc from pathlib import Path ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT / "recordings")) from harness import Recorder, boot_desk def main() -> None: boot_desk() import django from django.db import transaction from django.db.models import FETCH_ONE, FETCH_PEERS from django.utils import timezone from newsroom.models import Correction, Desk, Edition, Reporter, Story rec = Recorder("ch07-bench", subtitle=f"Django {django.__version__} on Python {platform.python_version()}: ch07-bench") now = timezone.now() # Seed temporary rows inside a rolled-back transaction for clean repeatable benchmarks desks = list(Desk.objects.order_by("id")) reporters = list(Reporter.objects.order_by("id")) edition = Edition.objects.order_by("id").first() # --- 1. N+1 wire comparison across 24 Story rows --- with transaction.atomic(): extra_stories = [ Story( headline=f"Wire story {i}", slug=f"wire-story-{i}", body="Long newsroom body copy " * 15, priority=2, status=Story.Status.PUBLISHED, published_at=now, desk=desks[i % len(desks)], reporter=reporters[i % len(reporters)], edition=edition, ) for i in range(18) ] Story.objects.bulk_create(extra_stories) all_stories = list(Story.objects.order_by("id")) Correction.objects.bulk_create( [Correction(story=s, note=f"Fix on {s.slug}", issued_at=now) for s in all_stories if s.slug.startswith("wire-story-")] ) n_stories = Story.objects.count() def run_fetch_one(): qs = Story.objects.fetch_mode(FETCH_ONE).order_by("id") return [(s.desk.name, s.reporter.name, len(list(s.corrections.all()))) for s in qs] def run_fetch_peers(): qs = Story.objects.fetch_mode(FETCH_PEERS).order_by("id") return [(s.desk.name, s.reporter.name, len(list(s.corrections.all()))) for s in qs] def run_peers_plus_prefetch(): qs = Story.objects.fetch_mode(FETCH_PEERS).prefetch_related("corrections").order_by("id") return [(s.desk.name, s.reporter.name, len(list(s.corrections.all()))) for s in qs] def run_eager(): qs = Story.objects.select_related("desk", "reporter").prefetch_related("corrections").order_by("id") return [(s.desk.name, s.reporter.name, len(list(s.corrections.all()))) for s in qs] # Verify identical output assert run_fetch_one() == run_fetch_peers() == run_peers_plus_prefetch() == run_eager() trials = 7 wire_rows = [] for label, fn in [ ("FETCH_ONE (naive N+1)", run_fetch_one), ("FETCH_PEERS (auto-batches FKs only)", run_fetch_peers), ("FETCH_PEERS + prefetch_related", run_peers_plus_prefetch), ("select_related + prefetch_related", run_eager), ]: with rec.capture_sql(log=False) as cap: fn() q_cnt = cap.count samples = [] for _ in range(trials): t0 = time.perf_counter() fn() samples.append((time.perf_counter() - t0) * 1000.0) wire_rows.append((label, q_cnt, statistics.median(samples))) # --- 2. Iterable hydration benchmark across 500 Story rows --- bulk_500 = [ Story( headline=f"Archive story {i}", slug=f"archive-story-{i}", body="Newsroom archival text " * 12, priority=(i % 3) + 1, status=Story.Status.PUBLISHED, published_at=now, desk=desks[i % len(desks)], reporter=reporters[i % len(reporters)], edition=edition, ) for i in range(500 - n_stories) ] Story.objects.bulk_create(bulk_500) total_500 = Story.objects.count() iter_specs = [ ("ModelIterable [all()]", lambda: list(Story.objects.all())), ("ModelIterable [only('id','headline','slug')]", lambda: list(Story.objects.only("id", "headline", "slug"))), ("ValuesIterable [values('id','headline','slug')]", lambda: list(Story.objects.values("id", "headline", "slug"))), ("ValuesListIterable [values_list(...)]", lambda: list(Story.objects.values_list("id", "headline", "slug"))), ("FlatValuesListIterable [flat=True]", lambda: list(Story.objects.values_list("slug", flat=True))), ] iter_results = [] for label, fn in iter_specs: fn() # warmup samples = [] for _ in range(7): t0 = time.perf_counter() fn() samples.append((time.perf_counter() - t0) * 1000.0) tracemalloc.start() _res = fn() _, peak = tracemalloc.get_traced_memory() tracemalloc.stop() del _res iter_results.append((label, statistics.median(samples), peak / 1024.0)) # --- 3. Bulk writes vs per-row loops across 200 Correction rows --- target_story = Story.objects.order_by("id").first() B = 200 write_results = [] def bench_write(label: str, fn) -> None: # warmup + sql count with transaction.atomic(): with rec.capture_sql(log=False) as cap: fn() sql_n = sum(1 for s, _ in cap.queries if not s.startswith(("SAVEPOINT", "RELEASE"))) transaction.set_rollback(True) samples = [] for _ in range(5): with transaction.atomic(): t0 = time.perf_counter() fn() samples.append((time.perf_counter() - t0) * 1000.0) transaction.set_rollback(True) write_results.append((label, sql_n, statistics.median(samples))) bench_write( "200x Correction.objects.create() [loop]", lambda: [Correction.objects.create(story=target_story, note=f"N{i}", issued_at=now) for i in range(B)], ) bench_write( "Correction.objects.bulk_create(200)", lambda: Correction.objects.bulk_create( [Correction(story=target_story, note=f"N{i}", issued_at=now) for i in range(B)] ), ) # Pre-seed 200 rows to compare update paths seeded = Correction.objects.bulk_create( [Correction(story=target_story, note=f"Seed {i}", issued_at=now) for i in range(B)] ) def upd_loop(): for idx, obj in enumerate(seeded): obj.note = f"Loop {idx}" obj.save(update_fields=["note"]) def upd_bulk(): for idx, obj in enumerate(seeded): obj.note = f"Bulk {idx}" Correction.objects.bulk_update(seeded, ["note"]) def upd_qs(): Correction.objects.filter(pk__in=[c.pk for c in seeded]).update(note="Uniform") bench_write("200x obj.save(update_fields=['note'])", upd_loop) bench_write("Correction.objects.bulk_update(200)", upd_bulk) bench_write("QuerySet.update() [uniform value]", upd_qs) transaction.set_rollback(True) with rec.block(f"N+1 wire comparison across {n_stories} stories (.desk + .reporter + .corrections, 7 trials)"): rec.emit(f"{'strategy':40} {'sql_queries':>11} {'median_ms':>10} {'relative':>10}") eager_ms = wire_rows[-1][2] for label, q_cnt, ms in wire_rows: rec.emit(f"{label:40} {q_cnt:11d} {ms:10.3f} {ms / eager_ms:9.2f}x") with rec.block(f"Iterable hydration across {total_500} Story rows (7 trials + tracemalloc peak KB)"): rec.emit(f"{'iterable':46} {'median_ms':>10} {'peak_kb':>10} {'relative':>10}") base_ms = iter_results[0][1] for label, ms, kb in iter_results: rec.emit(f"{label:46} {ms:10.3f} {kb:10.1f} {ms / base_ms:9.2f}x") with rec.block(f"Bulk writes vs per-row loops across {B} Correction rows (5 trials)"): rec.emit(f"{'operation':44} {'sql_queries':>11} {'median_ms':>10}") for label, sql_n, ms in write_results: rec.emit(f"{label:44} {sql_n:11d} {ms:10.3f}") rec.write() if __name__ == "__main__": main()