Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / scripts / maps / mamaps_build / src / timing.rs

timing.rs154 lines · 6.1 KiBRaw
1//! Gapless phase/subphase wall-clock timer for the maps pipeline.
2//!
3//! One `PhaseTimer` covers one tool run (which is one pipeline phase). Time is
4//! booked by *switching*: `switch("next")` stops the current subphase and starts
5//! the next one on the same instant, so subphases tile the phase wall with no
6//! gaps and no overlaps — the stop of every subphase is the start of the next.
7//! The summed subphases therefore equal the phase wall up to the microseconds
8//! the switch itself costs.
9//!
10//! The timer starts in an implicit `"other"` subphase, which also absorbs any
11//! stretch the caller never names. Callers name each major loop/pass and never
12//! need to account for setup/teardown explicitly: whatever is left in `"other"`
13//! at [`PhaseTimer::finish`] is the honest overhead bucket, not a fudge factor.
14//!
15//! Results leave the process as one parse-safe machine line on **stdout only**:
16//!
17//! ```text
18//! TIMING {"phase":"tiles","wall_s":123.456,"subphases":[{"name":"stage-a","s":12.345}]}
19//! ```
20//!
21//! Live progress meters stay on stderr (see `progress.rs`), warnings are
22//! `WARN: ...` on stderr, errors `ERROR: ...` on stderr. Nothing else on stdout
23//! may start with `TIMING `, and `TIMING` lines never go to stderr, so the
24//! orchestrator can split the streams without ambiguity.
25//!
26//! Contract, kept identical in every crate that carries a copy of this file
27//! (copies, not a shared crate: `gtfs_ingest` builds with zero dependencies,
28//! and `par.rs` / `progress.rs` already follow the same copy convention):
29//!
30//! * std only, no dependencies.
31//! * One timer per process, driven from the orchestrating (main) thread only.
32//! Worker threads never touch it; coarse loop/pass boundaries are the ticks.
33//! * `finish` merges repeat visits to the same subphase name (e.g. per-zoom
34//! `map`/`merge`/`encode`/`append`) by summing, preserving first-seen order,
35//! so fine-grained loops stay bounded instead of exploding the output.
36//! * Durations print with millisecond precision (`{:.3}` seconds).
37//! * Never one entry per feed / per tile / per feature: group those loops into
38//! one bounded subphase (e.g. `parse-feeds`, `encode`), the way per-zoom work
39//! folds into four totals here.
40
41use std::time::Instant;
42
43/// A single phase's gapless subphase chain. See the module docs.
44pub struct PhaseTimer {
45 phase: String,
46 start: Instant,
47 /// Name of the currently open subphase.
48 current: String,
49 /// When the currently open subphase started.
50 current_start: Instant,
51 /// Closed `(name, seconds)` segments, in close order.
52 segments: Vec<(String, f64)>,
53}
54
55impl PhaseTimer {
56 /// Start a phase clock. The clock opens in the `"other"` subphase, so any
57 /// work before the first [`PhaseTimer::switch`] is booked as overhead.
58 pub fn start(phase: &str) -> Self {
59 let now = Instant::now();
60 Self {
61 phase: phase.to_string(),
62 start: now,
63 current: "other".to_string(),
64 current_start: now,
65 segments: Vec::new(),
66 }
67 }
68
69 /// Close the current subphase and open `name`, on the same instant.
70 /// Repeat visits to a name are merged (summed) at [`PhaseTimer::finish`].
71 pub fn switch(&mut self, name: &str) {
72 let secs = self.current_start.elapsed().as_secs_f64();
73 let old = std::mem::replace(&mut self.current, name.to_string());
74 self.segments.push((old, secs));
75 self.current_start = Instant::now();
76 }
77
78 /// Close the current subphase, merge repeats, and emit the `TIMING` line.
79 /// Consumes the timer so a phase can only be reported once.
80 pub fn finish(mut self) {
81 self.close_current();
82 let wall = self.start.elapsed().as_secs_f64();
83 let mut merged: Vec<(String, f64)> = Vec::with_capacity(self.segments.len());
84 for (name, secs) in &self.segments {
85 match merged.iter_mut().find(|(n, _)| n == name) {
86 Some(slot) => slot.1 += secs,
87 None => merged.push((name.clone(), *secs)),
88 }
89 }
90 let mut subs = String::new();
91 for (i, (name, secs)) in merged.iter().enumerate() {
92 if i > 0 {
93 subs.push(',');
94 }
95 subs.push_str("{\"name\":\"");
96 esc_json(name, &mut subs);
97 subs.push_str(&format!("\",\"s\":{secs:.3}}}"));
98 }
99 let mut line = String::from("TIMING {\"phase\":\"");
100 esc_json(&self.phase, &mut line);
101 line.push_str(&format!("\",\"wall_s\":{wall:.3},\"subphases\":[{subs}]}}"));
102 println!("{line}");
103 }
104
105 fn close_current(&mut self) {
106 let secs = self.current_start.elapsed().as_secs_f64();
107 let name = std::mem::take(&mut self.current);
108 self.segments.push((name, secs));
109 }
110}
111
112/// Append `s` to `out` with JSON string escaping.
113fn esc_json(s: &str, out: &mut String) {
114 for c in s.chars() {
115 match c {
116 '"' => out.push_str("\\\""),
117 '\\' => out.push_str("\\\\"),
118 '\n' => out.push_str("\\n"),
119 '\r' => out.push_str("\\r"),
120 '\t' => out.push_str("\\t"),
121 c if (c as u32) < 0x20 => {
122 out.push_str(&format!("\\u{:04x}", c as u32));
123 }
124 c => out.push(c),
125 }
126 }
127}
128
129/// Emit one per-zoom machine line on stdout, next to (not instead of) the
130/// human-readable `zN ...` table row. Integer milliseconds — unlike the
131/// 0.1 s-rounded text row, these close the sum exactly.
132///
133/// `map_ms` / `merge_ms` / `encode_ms` / `append_ms` use the same meaning as
134/// the text table: per-zoom worker time in each tiling step.
135#[allow(clippy::too_many_arguments)]
136pub fn emit_zoom_row(
137 zoom: u8,
138 tiles: u64,
139 features: u64,
140 points: u64,
141 dropped: u64,
142 bytes: u64,
143 map_ms: u64,
144 merge_ms: u64,
145 encode_ms: u64,
146 append_ms: u64,
147) {
148 println!(
149 "TIMING {{\"zoom\":{zoom},\"tiles\":{tiles},\"features\":{features},\
150 \"points\":{points},\"dropped\":{dropped},\"bytes\":{bytes},\
151 \"map_ms\":{map_ms},\"merge_ms\":{merge_ms},\
152 \"encode_ms\":{encode_ms},\"append_ms\":{append_ms}}}"
153 );
154}