geolith-tiles-builder 0.4.2

Builds tiles from OpenStreetMap and Overture Maps: protomaps-schema vector PMTiles, Terrain-RGB, raster archives and 3D Tiles from Gaussian splats
Documentation
//! Planetiler-style phase timing and formatting.
//!
//! Provides elapsed-time logging, per-phase CPU/wall tracking, and compact
//! number/duration formatting for pipeline progress output.

use std::sync::OnceLock;
use std::time::{Duration, Instant};

/// Global program start instant, initialised once by [`init`].
static PROGRAM_START: OnceLock<Instant> = OnceLock::new();

/// Initialise the global program timer.  Call once at the top of `run()`.
pub fn init() {
    PROGRAM_START.get_or_init(Instant::now);
}

/// Seconds elapsed since [`init`] was called.
#[must_use]
pub fn elapsed() -> Duration {
    PROGRAM_START
        .get()
        .map_or(Duration::ZERO, |start| start.elapsed())
}

/// Format a [`Duration`] in human-readable compact form.
///
/// Examples: `"<1s"`, `"3s"`, `"0.2s"`, `"1m7s"`, `"7m20s"`, `"1h5m"`.
#[must_use]
pub fn format_duration(d: Duration) -> String {
    let secs = d.as_secs_f64();
    if secs < 1.0 {
        if secs < 0.05 {
            return "<1s".to_owned();
        }
        return format!("{secs:.1}s");
    }
    let total = d.as_secs();
    if total < 60 {
        return format!("{total}s");
    }
    let m = total / 60;
    let s = total % 60;
    if m < 60 {
        if s == 0 {
            return format!("{m}m");
        }
        return format!("{m}m{s}s");
    }
    let h = m / 60;
    let rm = m % 60;
    if rm == 0 {
        return format!("{h}h");
    }
    format!("{h}h{rm}m")
}

/// Format a count in compact human-readable form.
///
/// Examples: `"0"`, `"999"`, `"1k"`, `"31.9M"`, `"1.3B"`.
#[must_use]
pub fn format_count(n: u64) -> String {
    if n < 10_000 {
        return format!("{n}");
    }
    if n < 1_000_000 {
        let k = n as f64 / 1_000.0;
        if k >= 100.0 {
            return format!("{:.0}k", k);
        }
        if k >= 10.0 {
            return format!("{:.1}k", k);
        }
        return format!("{:.1}k", k);
    }
    if n < 1_000_000_000 {
        let m = n as f64 / 1_000_000.0;
        if m >= 100.0 {
            return format!("{:.0}M", m);
        }
        if m >= 10.0 {
            return format!("{:.1}M", m);
        }
        return format!("{:.1}M", m);
    }
    let b = n as f64 / 1_000_000_000.0;
    if b >= 10.0 {
        return format!("{:.1}B", b);
    }
    format!("{:.2}B", b)
}

// ---------------------------------------------------------------------------
// CPU time via getrusage
// ---------------------------------------------------------------------------

/// Snapshot of process CPU time (user + system).
#[derive(Debug, Clone, Copy)]
pub struct CpuTime {
    /// User CPU time.
    pub user: Duration,
    /// System CPU time.
    pub sys: Duration,
}

/// Read current process CPU time via `getrusage(RUSAGE_SELF)`.
#[must_use]
#[allow(
    unsafe_code,
    reason = "libc::getrusage fills a MaybeUninit; each unsafe block has a SAFETY comment"
)]
pub fn process_cpu_time() -> CpuTime {
    #[cfg(unix)]
    {
        let mut usage = std::mem::MaybeUninit::<libc::rusage>::uninit();
        // SAFETY: `getrusage` with `RUSAGE_SELF` writes into a valid `rusage`
        // struct. The pointer is valid because it comes from `MaybeUninit`.
        let ret = unsafe { libc::getrusage(libc::RUSAGE_SELF, usage.as_mut_ptr()) };
        if ret == 0 {
            // SAFETY: getrusage succeeded, so the struct is fully initialised.
            let ru = unsafe { usage.assume_init() };
            let user = Duration::new(
                ru.ru_utime.tv_sec as u64,
                (ru.ru_utime.tv_usec as u32) * 1000,
            );
            let sys = Duration::new(
                ru.ru_stime.tv_sec as u64,
                (ru.ru_stime.tv_usec as u32) * 1000,
            );
            return CpuTime { user, sys };
        }
        CpuTime {
            user: Duration::ZERO,
            sys: Duration::ZERO,
        }
    }
    #[cfg(not(unix))]
    {
        CpuTime {
            user: Duration::ZERO,
            sys: Duration::ZERO,
        }
    }
}

// ---------------------------------------------------------------------------
// PhaseTimer
// ---------------------------------------------------------------------------

/// Per-phase wall + CPU timer.
///
/// Created via `PhaseTimer::new`, captures start wall-clock and CPU time.
/// Call `PhaseTimer::finish` to compute the delta and log a summary.
pub struct PhaseTimer {
    name: &'static str,
    wall_start: Instant,
    cpu_start: CpuTime,
}

impl PhaseTimer {
    /// Create a new phase timer and log `"Starting..."`.
    pub fn start(name: &'static str) -> Self {
        let timer = Self {
            name,
            wall_start: Instant::now(),
            cpu_start: process_cpu_time(),
        };
        tracing::info!(target: "geolith", "[{}] Starting...", name);
        timer
    }

    /// Finish with an extra detail string appended to the log line.
    pub fn finish_with_detail(self, detail: &str) -> PhaseSummary {
        let wall = self.wall_start.elapsed();
        let cpu_end = process_cpu_time();
        let cpu_user = cpu_end.user.saturating_sub(self.cpu_start.user);
        let cpu_sys = cpu_end.sys.saturating_sub(self.cpu_start.sys);
        let cpu_total = cpu_user + cpu_sys;
        let avg = if wall.as_secs_f64() > 0.0 {
            cpu_total.as_secs_f64() / wall.as_secs_f64()
        } else {
            0.0
        };

        let detail_part = if detail.is_empty() {
            String::new()
        } else {
            format!(" {detail}")
        };

        tracing::info!(
            target: "geolith",
            "[{}] Finished in {} cpu:{} avg:{:.1}{}",
            self.name,
            format_duration(wall),
            format_duration(cpu_total),
            avg,
            detail_part,
        );

        PhaseSummary {
            name: self.name,
            wall,
            cpu_user,
            cpu_sys,
        }
    }
}

/// Summary returned by `PhaseTimer::finish`.
#[derive(Debug, Clone)]
pub struct PhaseSummary {
    /// Phase name.
    pub name: &'static str,
    /// Wall-clock duration.
    pub wall: Duration,
    /// User CPU time consumed during this phase.
    pub cpu_user: Duration,
    /// System CPU time consumed during this phase.
    pub cpu_sys: Duration,
}

// ---------------------------------------------------------------------------
// Custom tracing-subscriber FormatTime
// ---------------------------------------------------------------------------

/// A [`tracing_subscriber::fmt::time::FormatTime`] that prints elapsed time
/// since [`init`] in `H:MM:SS` format.
#[derive(Debug, Clone, Copy)]
pub struct ElapsedTimer;

impl tracing_subscriber::fmt::time::FormatTime for ElapsedTimer {
    fn format_time(&self, w: &mut tracing_subscriber::fmt::format::Writer<'_>) -> std::fmt::Result {
        let d = elapsed();
        let total_secs = d.as_secs();
        let h = total_secs / 3600;
        let m = (total_secs % 3600) / 60;
        let s = total_secs % 60;
        write!(w, "{h}:{m:02}:{s:02}")
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_format_duration() {
        assert_eq!(format_duration(Duration::from_millis(10)), "<1s");
        assert_eq!(format_duration(Duration::from_millis(200)), "0.2s");
        assert_eq!(format_duration(Duration::from_secs(3)), "3s");
        assert_eq!(format_duration(Duration::from_secs(47)), "47s");
        assert_eq!(format_duration(Duration::from_secs(67)), "1m7s");
        assert_eq!(format_duration(Duration::from_secs(440)), "7m20s");
        assert_eq!(format_duration(Duration::from_secs(120)), "2m");
        assert_eq!(format_duration(Duration::from_secs(3900)), "1h5m");
        assert_eq!(format_duration(Duration::from_secs(7200)), "2h");
    }

    #[test]
    fn test_format_count() {
        assert_eq!(format_count(0), "0");
        assert_eq!(format_count(999), "999");
        assert_eq!(format_count(9999), "9999");
        assert_eq!(format_count(10_000), "10.0k");
        assert_eq!(format_count(56_000), "56.0k");
        assert_eq!(format_count(520_000), "520k");
        assert_eq!(format_count(999_999), "1000k");
        assert_eq!(format_count(1_000_000), "1.0M");
        assert_eq!(format_count(4_500_000), "4.5M");
        assert_eq!(format_count(31_900_000), "31.9M");
        assert_eq!(format_count(842_000_000), "842M");
        assert_eq!(format_count(1_300_000_000), "1.30B");
    }

    #[test]
    fn format_count_edge_cases() {
        assert_eq!(format_count(1), "1");
        assert_eq!(format_count(50_000), "50.0k");
        assert_eq!(format_count(100_000), "100k");
        assert_eq!(format_count(2_000_000_000), "2.00B");
        assert_eq!(format_count(15_000_000_000), "15.0B");
    }

    #[test]
    fn format_duration_sub_50ms() {
        assert_eq!(format_duration(Duration::from_millis(0)), "<1s");
        assert_eq!(format_duration(Duration::from_millis(49)), "<1s");
        assert_eq!(format_duration(Duration::from_millis(50)), "0.1s");
    }

    #[test]
    fn phase_timer_finish_with_detail() {
        let timer = PhaseTimer::start("detailed");
        std::thread::sleep(Duration::from_millis(2));
        let summary = timer.finish_with_detail("extra info");
        assert_eq!(summary.name, "detailed");
    }

    #[test]
    fn elapsed_timer_format_time_writes_h_mm_ss() {
        use tracing_subscriber::fmt::format::Writer;
        use tracing_subscriber::fmt::time::FormatTime;

        init();
        let timer = ElapsedTimer;
        let mut buf = String::new();
        let mut writer = Writer::new(&mut buf);
        timer.format_time(&mut writer).expect("format");
        assert!(buf.contains(':'), "expected H:MM:SS format, got {:?}", buf);
        assert_eq!(buf.matches(':').count(), 2);
    }
}