Skip to main content

geolith_tiles_builder/
timing.rs

1//! Planetiler-style phase timing and formatting.
2//!
3//! Provides elapsed-time logging, per-phase CPU/wall tracking, and compact
4//! number/duration formatting for pipeline progress output.
5
6use std::sync::OnceLock;
7use std::time::{Duration, Instant};
8
9/// Global program start instant, initialised once by [`init`].
10static PROGRAM_START: OnceLock<Instant> = OnceLock::new();
11
12/// Initialise the global program timer.  Call once at the top of `run()`.
13pub fn init() {
14    PROGRAM_START.get_or_init(Instant::now);
15}
16
17/// Seconds elapsed since [`init`] was called.
18#[must_use]
19pub fn elapsed() -> Duration {
20    PROGRAM_START
21        .get()
22        .map_or(Duration::ZERO, |start| start.elapsed())
23}
24
25/// Format a [`Duration`] in human-readable compact form.
26///
27/// Examples: `"<1s"`, `"3s"`, `"0.2s"`, `"1m7s"`, `"7m20s"`, `"1h5m"`.
28#[must_use]
29pub fn format_duration(d: Duration) -> String {
30    let secs = d.as_secs_f64();
31    if secs < 1.0 {
32        if secs < 0.05 {
33            return "<1s".to_owned();
34        }
35        return format!("{secs:.1}s");
36    }
37    let total = d.as_secs();
38    if total < 60 {
39        return format!("{total}s");
40    }
41    let m = total / 60;
42    let s = total % 60;
43    if m < 60 {
44        if s == 0 {
45            return format!("{m}m");
46        }
47        return format!("{m}m{s}s");
48    }
49    let h = m / 60;
50    let rm = m % 60;
51    if rm == 0 {
52        return format!("{h}h");
53    }
54    format!("{h}h{rm}m")
55}
56
57/// Format a count in compact human-readable form.
58///
59/// Examples: `"0"`, `"999"`, `"1k"`, `"31.9M"`, `"1.3B"`.
60#[must_use]
61pub fn format_count(n: u64) -> String {
62    if n < 10_000 {
63        return format!("{n}");
64    }
65    if n < 1_000_000 {
66        let k = n as f64 / 1_000.0;
67        if k >= 100.0 {
68            return format!("{:.0}k", k);
69        }
70        if k >= 10.0 {
71            return format!("{:.1}k", k);
72        }
73        return format!("{:.1}k", k);
74    }
75    if n < 1_000_000_000 {
76        let m = n as f64 / 1_000_000.0;
77        if m >= 100.0 {
78            return format!("{:.0}M", m);
79        }
80        if m >= 10.0 {
81            return format!("{:.1}M", m);
82        }
83        return format!("{:.1}M", m);
84    }
85    let b = n as f64 / 1_000_000_000.0;
86    if b >= 10.0 {
87        return format!("{:.1}B", b);
88    }
89    format!("{:.2}B", b)
90}
91
92// ---------------------------------------------------------------------------
93// CPU time via getrusage
94// ---------------------------------------------------------------------------
95
96/// Snapshot of process CPU time (user + system).
97#[derive(Debug, Clone, Copy)]
98pub struct CpuTime {
99    /// User CPU time.
100    pub user: Duration,
101    /// System CPU time.
102    pub sys: Duration,
103}
104
105/// Read current process CPU time via `getrusage(RUSAGE_SELF)`.
106#[must_use]
107pub fn process_cpu_time() -> CpuTime {
108    #[cfg(unix)]
109    {
110        let mut usage = std::mem::MaybeUninit::<libc::rusage>::uninit();
111        // SAFETY: `getrusage` with `RUSAGE_SELF` writes into a valid `rusage`
112        // struct. The pointer is valid because it comes from `MaybeUninit`.
113        let ret = unsafe { libc::getrusage(libc::RUSAGE_SELF, usage.as_mut_ptr()) };
114        if ret == 0 {
115            // SAFETY: getrusage succeeded, so the struct is fully initialised.
116            let ru = unsafe { usage.assume_init() };
117            let user = Duration::new(
118                ru.ru_utime.tv_sec as u64,
119                (ru.ru_utime.tv_usec as u32) * 1000,
120            );
121            let sys = Duration::new(
122                ru.ru_stime.tv_sec as u64,
123                (ru.ru_stime.tv_usec as u32) * 1000,
124            );
125            return CpuTime { user, sys };
126        }
127        CpuTime {
128            user: Duration::ZERO,
129            sys: Duration::ZERO,
130        }
131    }
132    #[cfg(not(unix))]
133    {
134        CpuTime {
135            user: Duration::ZERO,
136            sys: Duration::ZERO,
137        }
138    }
139}
140
141// ---------------------------------------------------------------------------
142// PhaseTimer
143// ---------------------------------------------------------------------------
144
145/// Per-phase wall + CPU timer.
146///
147/// Created via [`PhaseTimer::new`], captures start wall-clock and CPU time.
148/// Call [`PhaseTimer::finish`] to compute the delta and log a summary.
149pub struct PhaseTimer {
150    name: &'static str,
151    wall_start: Instant,
152    cpu_start: CpuTime,
153}
154
155impl PhaseTimer {
156    /// Create a new phase timer and log `"Starting..."`.
157    pub fn start(name: &'static str) -> Self {
158        let timer = Self {
159            name,
160            wall_start: Instant::now(),
161            cpu_start: process_cpu_time(),
162        };
163        tracing::info!(target: "geolith", "[{}] Starting...", name);
164        timer
165    }
166
167    /// Finish with an extra detail string appended to the log line.
168    pub fn finish_with_detail(self, detail: &str) -> PhaseSummary {
169        let wall = self.wall_start.elapsed();
170        let cpu_end = process_cpu_time();
171        let cpu_user = cpu_end.user.saturating_sub(self.cpu_start.user);
172        let cpu_sys = cpu_end.sys.saturating_sub(self.cpu_start.sys);
173        let cpu_total = cpu_user + cpu_sys;
174        let avg = if wall.as_secs_f64() > 0.0 {
175            cpu_total.as_secs_f64() / wall.as_secs_f64()
176        } else {
177            0.0
178        };
179
180        let detail_part = if detail.is_empty() {
181            String::new()
182        } else {
183            format!(" {detail}")
184        };
185
186        tracing::info!(
187            target: "geolith",
188            "[{}] Finished in {} cpu:{} avg:{:.1}{}",
189            self.name,
190            format_duration(wall),
191            format_duration(cpu_total),
192            avg,
193            detail_part,
194        );
195
196        PhaseSummary {
197            name: self.name,
198            wall,
199            cpu_user,
200            cpu_sys,
201        }
202    }
203}
204
205/// Summary returned by [`PhaseTimer::finish`].
206#[derive(Debug, Clone)]
207pub struct PhaseSummary {
208    /// Phase name.
209    pub name: &'static str,
210    /// Wall-clock duration.
211    pub wall: Duration,
212    /// User CPU time consumed during this phase.
213    pub cpu_user: Duration,
214    /// System CPU time consumed during this phase.
215    pub cpu_sys: Duration,
216}
217
218// ---------------------------------------------------------------------------
219// Custom tracing-subscriber FormatTime
220// ---------------------------------------------------------------------------
221
222/// A [`tracing_subscriber::fmt::time::FormatTime`] that prints elapsed time
223/// since [`init`] in `H:MM:SS` format.
224#[derive(Debug, Clone, Copy)]
225pub struct ElapsedTimer;
226
227impl tracing_subscriber::fmt::time::FormatTime for ElapsedTimer {
228    fn format_time(&self, w: &mut tracing_subscriber::fmt::format::Writer<'_>) -> std::fmt::Result {
229        let d = elapsed();
230        let total_secs = d.as_secs();
231        let h = total_secs / 3600;
232        let m = (total_secs % 3600) / 60;
233        let s = total_secs % 60;
234        write!(w, "{h}:{m:02}:{s:02}")
235    }
236}
237
238// ---------------------------------------------------------------------------
239// Tests
240// ---------------------------------------------------------------------------
241
242#[cfg(test)]
243mod tests {
244    use super::*;
245
246    #[test]
247    fn test_format_duration() {
248        assert_eq!(format_duration(Duration::from_millis(10)), "<1s");
249        assert_eq!(format_duration(Duration::from_millis(200)), "0.2s");
250        assert_eq!(format_duration(Duration::from_secs(3)), "3s");
251        assert_eq!(format_duration(Duration::from_secs(47)), "47s");
252        assert_eq!(format_duration(Duration::from_secs(67)), "1m7s");
253        assert_eq!(format_duration(Duration::from_secs(440)), "7m20s");
254        assert_eq!(format_duration(Duration::from_secs(120)), "2m");
255        assert_eq!(format_duration(Duration::from_secs(3900)), "1h5m");
256        assert_eq!(format_duration(Duration::from_secs(7200)), "2h");
257    }
258
259    #[test]
260    fn test_format_count() {
261        assert_eq!(format_count(0), "0");
262        assert_eq!(format_count(999), "999");
263        assert_eq!(format_count(9999), "9999");
264        assert_eq!(format_count(10_000), "10.0k");
265        assert_eq!(format_count(56_000), "56.0k");
266        assert_eq!(format_count(520_000), "520k");
267        assert_eq!(format_count(999_999), "1000k");
268        assert_eq!(format_count(1_000_000), "1.0M");
269        assert_eq!(format_count(4_500_000), "4.5M");
270        assert_eq!(format_count(31_900_000), "31.9M");
271        assert_eq!(format_count(842_000_000), "842M");
272        assert_eq!(format_count(1_300_000_000), "1.30B");
273    }
274
275    #[test]
276    fn format_count_edge_cases() {
277        assert_eq!(format_count(1), "1");
278        assert_eq!(format_count(50_000), "50.0k");
279        assert_eq!(format_count(100_000), "100k");
280        assert_eq!(format_count(2_000_000_000), "2.00B");
281        assert_eq!(format_count(15_000_000_000), "15.0B");
282    }
283
284    #[test]
285    fn format_duration_sub_50ms() {
286        assert_eq!(format_duration(Duration::from_millis(0)), "<1s");
287        assert_eq!(format_duration(Duration::from_millis(49)), "<1s");
288        assert_eq!(format_duration(Duration::from_millis(50)), "0.1s");
289    }
290
291    #[test]
292    fn phase_timer_finish_with_detail() {
293        let timer = PhaseTimer::start("detailed");
294        std::thread::sleep(Duration::from_millis(2));
295        let summary = timer.finish_with_detail("extra info");
296        assert_eq!(summary.name, "detailed");
297    }
298
299    #[test]
300    fn elapsed_timer_format_time_writes_h_mm_ss() {
301        use tracing_subscriber::fmt::format::Writer;
302        use tracing_subscriber::fmt::time::FormatTime;
303
304        init();
305        let timer = ElapsedTimer;
306        let mut buf = String::new();
307        let mut writer = Writer::new(&mut buf);
308        timer.format_time(&mut writer).expect("format");
309        assert!(buf.contains(':'), "expected H:MM:SS format, got {:?}", buf);
310        assert_eq!(buf.matches(':').count(), 2);
311    }
312}