17/36
Part 5 of 8 · Events and timeLearn and do
Start and end events nest like brackets
Eight samples give eight events
Here are eight samples of a short run, taken every 10 ms. Below them are the events that events_between gives on each neighboring pair, with what's still open closed at the last sample:
SAMPLES = [
(0, ["main"]),
(10, ["main", "load"]),
(20, ["main", "load", "parse"]),
(30, ["main", "load", "parse"]),
(40, ["main", "save"]),
(50, ["main", "save"]),
(60, ["main", "save"]),
(70, ["main"]),
]
EVENTS = [
(0, "start", "main"),
(10, "start", "load"),
(20, "start", "parse"),
(40, "end", "parse"),
(40, "end", "load"),
(40, "start", "save"),
(70, "end", "save"),
(70, "end", "main"),
]
print(len(SAMPLES), "samples,", len(EVENTS), "events")
8 samples, 8 events
Write each start as ( and each end as ), and the eight events read ((())()): balanced brackets. Every start has an end, and a call can't end while a call it made is still open. Drawn over time, each call is a bar that sits inside its caller's bar:
main
load
parse
save
010203040506070
ms
That nesting makes timing them a stack problem.
In the editor, write as_brackets(events), which turns a list of events into its bracket string. Then write nests(events), which checks with a stack that each end closes the innermost open call and nothing is left open.