#!/usr/bin/env python3 """Timing benchmarks for Chapter 10 (Templates and forms) on Django 6.1.3. Measures: 1. Uncached filesystem template loader vs. cached template loader (and debug=True DebugLexer vs. debug=False Lexer) rendering desk's newsroom/edition.html (extending newsroom/base.html) across 7 trials. 2. Form instantiation + validation cost across plain Form, StoryForm (ModelForm with 3 ModelChoiceFields + validate_unique), and a 10-form CorrectionFormSet across 7 trials. """ from __future__ import annotations import statistics import sys import time from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) from harness import Recorder, boot_desk def bench_us(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) * 1e6 / iters) return statistics.median(samples) def main() -> None: boot_desk() from django import forms from django.forms import formset_factory from django.template import Context, Engine from newsroom.forms import StoryForm from newsroom.models import Desk, Edition, Reporter, Story rec = Recorder("ch10-bench") templates_dir = str(Path(__file__).resolve().parent.parent / "desk" / "newsroom" / "templates") edition = Edition.objects.get(slug="2026-11-25") stories = list( Story.objects.filter(edition=edition, status=Story.Status.PUBLISHED) .select_related("desk", "reporter") .prefetch_related("corrections") ) ctx_data = {"edition": edition, "stories": stories} eng_uncached_dbg = Engine( dirs=[templates_dir], debug=True, loaders=["django.template.loaders.filesystem.Loader"], ) eng_uncached = Engine( dirs=[templates_dir], debug=False, loaders=["django.template.loaders.filesystem.Loader"], ) eng_cached_dbg = Engine( dirs=[templates_dir], debug=True, loaders=[ ( "django.template.loaders.cached.Loader", ["django.template.loaders.filesystem.Loader"], ) ], ) eng_cached = Engine( dirs=[templates_dir], debug=False, loaders=[ ( "django.template.loaders.cached.Loader", ["django.template.loaders.filesystem.Loader"], ) ], ) tpl_modes = [ ("uncached + debug=True", eng_uncached_dbg, 300), ("uncached + debug=False", eng_uncached, 300), ("cached + debug=True", eng_cached_dbg, 800), ("cached + debug=False", eng_cached, 800), ] with rec.block("1. Template get_template + render of edition.html (7 trials, us/render)"): rec.emit(f"{'loader_mode':<26} {'median_us':>10} {'speedup':>9}") base_us = None for label, eng, iters in tpl_modes: med = bench_us( lambda e=eng: e.get_template("newsroom/edition.html").render(Context(ctx_data)), iters=iters, trials=7, ) if base_us is None: base_us = med rec.emit(f"{label:<26} {med:10.1f} {base_us / med:8.2f}x") # Part 2: Form instantiation and validation costs class PlainNoteForm(forms.Form): headline = forms.CharField(max_length=160) priority = forms.IntegerField(min_value=1, max_value=5) PlainFormSet = formset_factory(PlainNoteForm, extra=0) metro = Desk.objects.get(slug="metro") ada = Reporter.objects.get(name="Ada") story_post = { "headline": "Council approves ferry dock", "slug": "council-approves-ferry-dock", "desk": str(metro.pk), "reporter": str(ada.pk), "edition": str(edition.pk), "priority": "1", "body": "Lead paragraph.", } plain_post = {"headline": "Short note", "priority": "2"} fs_post = { "form-TOTAL_FORMS": "10", "form-INITIAL_FORMS": "0", "form-MIN_NUM_FORMS": "0", "form-MAX_NUM_FORMS": "1000", } for i in range(10): fs_post[f"form-{i}-headline"] = f"Note {i}" fs_post[f"form-{i}-priority"] = "2" with rec.block("2. Form instantiation and full_clean() cost (7 trials, us/op)"): rec.emit(f"{'form_op':<34} {'median_us':>10} {'rel':>8}") f_rows = [ ("PlainForm() unbound (deepcopy)", lambda: PlainNoteForm(), 2000), ("PlainForm(post).is_valid()", lambda: PlainNoteForm(plain_post).is_valid(), 1500), ("StoryForm() unbound (7 fields)", lambda: StoryForm(), 1000), ("StoryForm(post).is_valid() [DB]", lambda: StoryForm(story_post).is_valid(), 200), ("FormSet(10 PlainForms).is_valid()", lambda: PlainFormSet(fs_post).is_valid(), 250), ] ref_us = None for label, fn, iters in f_rows: med = bench_us(fn, iters=iters, trials=7) if ref_us is None: ref_us = med rec.emit(f"{label:<34} {med:10.1f} {med / ref_us:7.2f}x") rec.write() if __name__ == "__main__": main()