#!/usr/bin/env python3 """Measured timing benchmarks for Chapter 2 (Booting Django). Measures: 1. LazySettings attribute read cost over 500,000 reads (median of 5 trials): - plain object attribute read (baseline) - cached settings.DEBUG hit via LazySettings.__dict__ - uncached LazySettings.__getattr__('DEBUG') proxy path 2. Cold django.setup() millisecond breakdown across 5 fresh Python subprocesses booting desk/: - Settings.__init__ (inside first settings read) - configure_logging (excluding Settings.__init__) - Phase 1: AppConfig.create x 8 - Phase 2: AppConfig.import_models x 8 - Phase 3: AppConfig.ready x 8 (including AdminConfig.ready -> autodiscover) """ from __future__ import annotations import json import os import platform import statistics import subprocess import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parent.parent DESK_DIR = ROOT / "desk" sys.path.insert(0, str(Path(__file__).resolve().parent)) sys.path.insert(0, str(DESK_DIR)) from harness import Recorder # noqa: E402 os.environ["DJANGO_SETTINGS_MODULE"] = "desk.settings" import django # noqa: E402 from django.conf import LazySettings, settings # noqa: E402 rec = Recorder( "ch02-bench", f"Django {django.get_version()} on Python {platform.python_version()}: ch02-bench", ) # --- Benchmark 1: LazySettings __dict__ cache vs __getattr__ proxy --- _ = settings.DEBUG # warm settings so DEBUG is in settings.__dict__ wrapped = settings._wrapped class PlainHolder: DEBUG = False plain = PlainHolder() N = 500_000 TRIALS = 5 def time_reads(fn, n: int = N) -> float: t0 = time.perf_counter_ns() fn(n) return (time.perf_counter_ns() - t0) / n def read_plain(n: int) -> None: obj = plain for _ in range(n): _ = obj.DEBUG def read_cached_settings(n: int) -> None: s = settings for _ in range(n): _ = s.DEBUG def read_uncached_proxy(n: int) -> None: # Call LazySettings.__getattr__ directly, simulating a proxy without __dict__ caching. s = settings fn = LazySettings.__getattr__ for _ in range(n): fn(s, "DEBUG") plain_ns = statistics.median(time_reads(read_plain) for _ in range(TRIALS)) cached_ns = statistics.median(time_reads(read_cached_settings) for _ in range(TRIALS)) proxy_ns = statistics.median(time_reads(read_uncached_proxy) for _ in range(TRIALS)) with rec.block(f"LazySettings read cost ({N:,} reads, median of {TRIALS} trials, nanoseconds per read)"): rec.emit("path ns_per_read relative") rec.emit(f"plain object attribute {plain_ns:6.1f} 1.0x") rec.emit(f"settings.DEBUG (__dict__ cache hit) {cached_ns:6.1f} {cached_ns / plain_ns:.1f}x") rec.emit(f"LazySettings.__getattr__ (no cache) {proxy_ns:6.1f} {proxy_ns / plain_ns:.1f}x") rec.emit(f"self-caching speedup (__getattr__ / __dict__): {proxy_ns / cached_ns:.1f}x faster") # --- Benchmark 2: Cold django.setup() phase breakdown in 5 fresh subprocesses --- COLD_PROBE = r""" import json, os, time os.environ["DJANGO_SETTINGS_MODULE"] = "desk.settings" import django from django.apps.config import AppConfig from django.conf import Settings from django.utils import log as django_log t = {"urls_import": 0.0, "settings": 0.0, "logging": 0.0, "phase1": 0.0, "phase2": 0.0, "phase3": 0.0} orig_settings_init = Settings.__init__ def timed_settings_init(self, mod): t0 = time.perf_counter() try: return orig_settings_init(self, mod) finally: t["settings"] += (time.perf_counter() - t0) * 1000.0 Settings.__init__ = timed_settings_init orig_cfg_log = django_log.configure_logging def timed_cfg_log(cfg, settings_dict): t0 = time.perf_counter() try: return orig_cfg_log(cfg, settings_dict) finally: t["logging"] += (time.perf_counter() - t0) * 1000.0 django_log.configure_logging = timed_cfg_log orig_create = AppConfig.create.__func__ @classmethod def timed_create(cls, entry): t0 = time.perf_counter() cfg = orig_create(cls, entry) t["phase1"] += (time.perf_counter() - t0) * 1000.0 orig_ready = cfg.ready def timed_ready(): r0 = time.perf_counter() try: return orig_ready() finally: t["phase3"] += (time.perf_counter() - r0) * 1000.0 cfg.ready = timed_ready return cfg AppConfig.create = timed_create orig_import_models = AppConfig.import_models def timed_import_models(self): t0 = time.perf_counter() try: return orig_import_models(self) finally: t["phase2"] += (time.perf_counter() - t0) * 1000.0 AppConfig.import_models = timed_import_models t0 = time.perf_counter() # Measure the exact import django.setup() runs on line 16 before configure_logging. import django.urls # noqa: F401 t1 = time.perf_counter() t["urls_import"] = (t1 - t0) * 1000.0 django.setup() t["total"] = (time.perf_counter() - t0) * 1000.0 print(json.dumps(t)) """ env = os.environ.copy() env["PYTHONPATH"] = str(DESK_DIR) runs: list[dict[str, float]] = [] for _ in range(5): proc = subprocess.run( [sys.executable, "-c", COLD_PROBE], cwd=str(ROOT), env=env, capture_output=True, text=True, check=True, ) runs.append(json.loads(proc.stdout.strip())) keys = ("urls_import", "settings", "logging", "phase1", "phase2", "phase3", "total") med = {k: statistics.median(r[k] for r in runs) for k in keys} least_total = min(r["total"] for r in runs) with rec.block("Cold django.setup() breakdown on desk/ (5 fresh Python subprocesses, milliseconds)"): rec.emit("stage median_ms share") total = med["total"] for label, key in ( ("import django.urls (setup line 16)", "urls_import"), ("Settings.__init__ (desk.settings)", "settings"), ("configure_logging (dictConfig)", "logging"), ("Phase 1: AppConfig.create x 8", "phase1"), ("Phase 2: import_models x 8", "phase2"), ("Phase 3: AppConfig.ready x 8", "phase3"), ): val = med[key] rec.emit(f"{label:<34s} {val:6.2f} {val / total * 100:5.1f}%") rec.emit(f"{'Total django.setup()':<34s} {total:6.2f} (least {least_total:.2f} ms)") rec.write()