A clinic simulation¶
A seeded simulation of a clinic over 2,000 days, run three times with six,
seven, and eight doctors. Patients arrive at random, wait in order of
urgency, and are seen by the next free doctor. It uses random, heapq,
and math, a table of constants at module level, and two dataclasses that
cross between Python and native code under ppy run.
Run it¶
What it prints¶
python clinic.ppy, ppy run clinic.ppy, ppy build --standalone clinic.ppy -o dist && ./dist/clinic
6 doctors:
day 0: 395 seen, 202 late, longest wait 382.6 min
day 500: 442 seen, 266 late, longest wait 486.3 min
day 1000: 403 seen, 179 late, longest wait 362.4 min
day 1500: 378 seen, 193 late, longest wait 382.4 min
2000 days, 799475 patients, 55.67% late, mean wait 180.7 min, worst 632.7 min
7 doctors:
day 0: 395 seen, 109 late, longest wait 201.3 min
day 500: 442 seen, 254 late, longest wait 344.2 min
day 1000: 403 seen, 29 late, longest wait 138.8 min
day 1500: 378 seen, 78 late, longest wait 174.0 min
2000 days, 799475 patients, 39.34% late, mean wait 97.0 min, worst 504.6 min
8 doctors:
day 0: 395 seen, 0 late, longest wait 38.5 min
day 500: 442 seen, 197 late, longest wait 201.4 min
day 1000: 403 seen, 0 late, longest wait 80.2 min
day 1500: 378 seen, 0 late, longest wait 60.9 min
2000 days, 799475 patients, 10.75% late, mean wait 40.2 min, worst 364.4 min
The program¶
SHARE,CARE, andLATEare tuples of three floats at module level, one entry per triage level, most urgent first: the share of arrivals, the mean minutes a doctor takes, and how long a patient may wait before the wait counts as late.Clinicis a dataclass of three numbers: doctors, arrivals per hour, and the seed.Reportis a dataclass that adds up the days;add_daywrites its fields.one_daydraws the day's arrivals withrandom.expovariate, gives each a level fromrandom.random()throughlevel_of, and pushes them onto a heap of events. It then pops events in time order. A waiting patient goes on a second heap ordered by level and arrival time. Each time a doctor is free, the most urgent patient is seen for a time drawn fromrandom.lognormvariatearoundmath.log(CARE[level]). The day goes into the report, and every 500th day prints a line.run(clinic, days=30)seeds the generator from the clinic, makes aReport, runs the days, and returns the report.mainmakes aClinicfor each number of doctors, callsrun(clinic, days=2000), and prints the share of late patients and the waits. Every run draws the same arrivals, since every clinic has the same seed, so the three lines differ only in the number of doctors.
How it runs natively¶
ppy explain clinic.level_of, clinic.one_day, clinic.run, and
clinic.Report.add_day each say llvm backend: native.
SHARE[level]reads a module-level tuple with an index computed at run time. A tuple of numbers bound once at module level is a constant: native code builds it once per call and picks the item by comparing the index with each position, after the same bounds check CPython makes. Being a constant, it also reaches the standalone binary.random.expovariate,random.random, andrandom.lognormvariateare CPython's algorithms on CPython's Mersenne Twister. Underppy run, native code draws from the generator Python'srandomuses, so the seed inrungives the same numbers on every path.heapq.heappushandheappopon lists of tuples make the same comparisons as CPython, so the heaps pop in the same order and ties break the same way.mainreturns nothing, so it has no Python boundary of its own: underppy run, Python runsmain, andrunis the native call it makes. TheClinicargument crosses as its three fields.days=2000is a keyword argument, which the boundary binds the way Python binds it, with the default for anything left out. TheReportthat native code made comes back as a newReportinstance with its fields set.one_day(clinic, report, day)leaveshoursto its default. Native callers bind keywords and constant defaults when the module is compiled.- The lines
one_dayprints are held whilerunruns and written when it returns, in the order they were printed.
Timing¶
Wall time for the whole program, the mean of five runs, measured from a
checkout under /tmp on one machine (Python 3.14, an Intel Core Ultra 9
386H under WSL2):
| seconds | |
|---|---|
python clinic.ppy |
2.73 |
ppy run clinic.ppy, after the first run built the cache |
1.11 |
./dist/clinic, the standalone binary |
1.08 |
ppy run also starts CPython, names the cached build from the project's
sources, and loads its native library, which the standalone binary does
not pay.
Where the code comes from¶
clinic.ppy is hand-written.
Read on: the standard library guide and classes at the boundary.
51_clinic/clinic.ppy¶
import heapq
import math
import random
from dataclasses import dataclass
SHARE: tuple[float, float, float] = (0.1, 0.3, 0.6)
CARE: tuple[float, float, float] = (25.0, 15.0, 8.0)
LATE: tuple[float, float, float] = (10.0, 30.0, 120.0)
@dataclass
class Clinic:
doctors: int
arrivals_per_hour: float
seed: int
@dataclass
class Report:
days: int = 0
seen: int = 0
late: int = 0
worst: float = 0.0
total_wait: float = 0.0
def add_day(self, seen: int, late: int, longest: float, waited: float) -> None:
self.days += 1
self.seen += seen
self.late += late
self.worst = max(self.worst, longest)
self.total_wait += waited
def level_of(draw: float) -> int:
edge = 0.0
for level in range(3):
edge += SHARE[level]
if draw < edge:
return level
return 2
def one_day(clinic: Clinic, report: Report, day: int, hours: float = 10.0) -> None:
rate = clinic.arrivals_per_hour / 60.0
events: list[tuple[float, int, int]] = []
clock = random.expovariate(rate)
while clock < hours * 60.0:
heapq.heappush(events, (clock, 0, level_of(random.random())))
clock += random.expovariate(rate)
waiting: list[tuple[int, float]] = []
free = clinic.doctors
seen = late = 0
longest = waited = 0.0
while events:
now, kind, level = heapq.heappop(events)
if kind == 0:
heapq.heappush(waiting, (level, now))
else:
free += 1
while free > 0 and waiting:
urgency, came = heapq.heappop(waiting)
wait = now - came
waited += wait
longest = max(longest, wait)
if wait > LATE[urgency]:
late += 1
seen += 1
free -= 1
care = random.lognormvariate(math.log(CARE[urgency]), 0.4)
heapq.heappush(events, (now + care, 1, urgency))
report.add_day(seen, late, longest, waited)
if day % 500 == 0:
print(f" day {day:3d}: {seen} seen, {late} late, longest wait {longest:.1f} min")
def run(clinic: Clinic, days: int = 30) -> Report:
random.seed(clinic.seed)
report = Report()
for day in range(days):
one_day(clinic, report, day)
return report
def main() -> None:
for doctors in (6, 7, 8):
clinic = Clinic(doctors=doctors, arrivals_per_hour=40.0, seed=2026)
print(f"{doctors} doctors:")
report = run(clinic, days=2000)
share = 100.0 * report.late / report.seen
mean = report.total_wait / report.seen
print(
f" {report.days} days, {report.seen} patients, {share:.2f}% late, "
f"mean wait {mean:.1f} min, worst {report.worst:.1f} min"
)
main()
Source: examples/51_clinic.