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]
107#[allow(
108    unsafe_code,
109    reason = "libc::getrusage fills a MaybeUninit; each unsafe block has a SAFETY comment"
110)]
111pub fn process_cpu_time() -> CpuTime {
112    #[cfg(unix)]
113    {
114        let mut usage = std::mem::MaybeUninit::<libc::rusage>::uninit();
115        // SAFETY: `getrusage` with `RUSAGE_SELF` writes into a valid `rusage`
116        // struct. The pointer is valid because it comes from `MaybeUninit`.
117        let ret = unsafe { libc::getrusage(libc::RUSAGE_SELF, usage.as_mut_ptr()) };
118        if ret == 0 {
119            // SAFETY: getrusage succeeded, so the struct is fully initialised.
120            let ru = unsafe { usage.assume_init() };
121            let user = Duration::new(
122                ru.ru_utime.tv_sec as u64,
123                (ru.ru_utime.tv_usec as u32) * 1000,
124            );
125            let sys = Duration::new(
126                ru.ru_stime.tv_sec as u64,
127                (ru.ru_stime.tv_usec as u32) * 1000,
128            );
129            return CpuTime { user, sys };
130        }
131        CpuTime {
132            user: Duration::ZERO,
133            sys: Duration::ZERO,
134        }
135    }
136    #[cfg(not(unix))]
137    {
138        CpuTime {
139            user: Duration::ZERO,
140            sys: Duration::ZERO,
141        }
142    }
143}
144
145// ---------------------------------------------------------------------------
146// PhaseTimer
147// ---------------------------------------------------------------------------
148
149/// Per-phase wall + CPU timer.
150///
151/// Created via `PhaseTimer::new`, captures start wall-clock and CPU time.
152/// Call `PhaseTimer::finish` to compute the delta and log a summary.
153pub struct PhaseTimer {
154    name: &'static str,
155    wall_start: Instant,
156    cpu_start: CpuTime,
157}
158
159impl PhaseTimer {
160    /// Create a new phase timer and log `"Starting..."`.
161    pub fn start(name: &'static str) -> Self {
162        let timer = Self {
163            name,
164            wall_start: Instant::now(),
165            cpu_start: process_cpu_time(),
166        };
167        tracing::info!(target: "geolith", "[{}] Starting...", name);
168        timer
169    }
170
171    /// Finish with an extra detail string appended to the log line.
172    pub fn finish_with_detail(self, detail: &str) -> PhaseSummary {
173        let wall = self.wall_start.elapsed();
174        let cpu_end = process_cpu_time();
175        let cpu_user = cpu_end.user.saturating_sub(self.cpu_start.user);
176        let cpu_sys = cpu_end.sys.saturating_sub(self.cpu_start.sys);
177        let cpu_total = cpu_user + cpu_sys;
178        let avg = if wall.as_secs_f64() > 0.0 {
179            cpu_total.as_secs_f64() / wall.as_secs_f64()
180        } else {
181            0.0
182        };
183
184        let detail_part = if detail.is_empty() {
185            String::new()
186        } else {
187            format!(" {detail}")
188        };
189
190        tracing::info!(
191            target: "geolith",
192            "[{}] Finished in {} cpu:{} avg:{:.1}{}",
193            self.name,
194            format_duration(wall),
195            format_duration(cpu_total),
196            avg,
197            detail_part,
198        );
199
200        PhaseSummary {
201            name: self.name,
202            wall,
203            cpu_user,
204            cpu_sys,
205        }
206    }
207}
208
209/// Summary returned by `PhaseTimer::finish`.
210#[derive(Debug, Clone)]
211pub struct PhaseSummary {
212    /// Phase name.
213    pub name: &'static str,
214    /// Wall-clock duration.
215    pub wall: Duration,
216    /// User CPU time consumed during this phase.
217    pub cpu_user: Duration,
218    /// System CPU time consumed during this phase.
219    pub cpu_sys: Duration,
220}
221
222// ---------------------------------------------------------------------------
223// Custom tracing-subscriber FormatTime
224// ---------------------------------------------------------------------------
225
226/// A [`tracing_subscriber::fmt::time::FormatTime`] that prints elapsed time
227/// since [`init`] in `H:MM:SS` format.
228#[derive(Debug, Clone, Copy)]
229pub struct ElapsedTimer;
230
231impl tracing_subscriber::fmt::time::FormatTime for ElapsedTimer {
232    fn format_time(&self, w: &mut tracing_subscriber::fmt::format::Writer<'_>) -> std::fmt::Result {
233        let d = elapsed();
234        let total_secs = d.as_secs();
235        let h = total_secs / 3600;
236        let m = (total_secs % 3600) / 60;
237        let s = total_secs % 60;
238        write!(w, "{h}:{m:02}:{s:02}")
239    }
240}
241
242// ---------------------------------------------------------------------------
243// Tests
244// ---------------------------------------------------------------------------
245
246#[cfg(test)]
247mod tests {
248    use super::*;
249
250    #[test]
251    fn test_format_duration() {
252        assert_eq!(format_duration(Duration::from_millis(10)), "<1s");
253        assert_eq!(format_duration(Duration::from_millis(200)), "0.2s");
254        assert_eq!(format_duration(Duration::from_secs(3)), "3s");
255        assert_eq!(format_duration(Duration::from_secs(47)), "47s");
256        assert_eq!(format_duration(Duration::from_secs(67)), "1m7s");
257        assert_eq!(format_duration(Duration::from_secs(440)), "7m20s");
258        assert_eq!(format_duration(Duration::from_secs(120)), "2m");
259        assert_eq!(format_duration(Duration::from_secs(3900)), "1h5m");
260        assert_eq!(format_duration(Duration::from_secs(7200)), "2h");
261    }
262
263    #[test]
264    fn test_format_count() {
265        assert_eq!(format_count(0), "0");
266        assert_eq!(format_count(999), "999");
267        assert_eq!(format_count(9999), "9999");
268        assert_eq!(format_count(10_000), "10.0k");
269        assert_eq!(format_count(56_000), "56.0k");
270        assert_eq!(format_count(520_000), "520k");
271        assert_eq!(format_count(999_999), "1000k");
272        assert_eq!(format_count(1_000_000), "1.0M");
273        assert_eq!(format_count(4_500_000), "4.5M");
274        assert_eq!(format_count(31_900_000), "31.9M");
275        assert_eq!(format_count(842_000_000), "842M");
276        assert_eq!(format_count(1_300_000_000), "1.30B");
277    }
278
279    #[test]
280    fn format_count_edge_cases() {
281        assert_eq!(format_count(1), "1");
282        assert_eq!(format_count(50_000), "50.0k");
283        assert_eq!(format_count(100_000), "100k");
284        assert_eq!(format_count(2_000_000_000), "2.00B");
285        assert_eq!(format_count(15_000_000_000), "15.0B");
286    }
287
288    #[test]
289    fn format_duration_sub_50ms() {
290        assert_eq!(format_duration(Duration::from_millis(0)), "<1s");
291        assert_eq!(format_duration(Duration::from_millis(49)), "<1s");
292        assert_eq!(format_duration(Duration::from_millis(50)), "0.1s");
293    }
294
295    #[test]
296    fn phase_timer_finish_with_detail() {
297        let timer = PhaseTimer::start("detailed");
298        std::thread::sleep(Duration::from_millis(2));
299        let summary = timer.finish_with_detail("extra info");
300        assert_eq!(summary.name, "detailed");
301    }
302
303    #[test]
304    fn elapsed_timer_format_time_writes_h_mm_ss() {
305        use tracing_subscriber::fmt::format::Writer;
306        use tracing_subscriber::fmt::time::FormatTime;
307
308        init();
309        let timer = ElapsedTimer;
310        let mut buf = String::new();
311        let mut writer = Writer::new(&mut buf);
312        timer.format_time(&mut writer).expect("format");
313        assert!(buf.contains(':'), "expected H:MM:SS format, got {:?}", buf);
314        assert_eq!(buf.matches(':').count(), 2);
315    }
316}