Skip to main content

docling_pdf/
timing.rs

1//! Lightweight, env-gated per-stage timing for profiling the PDF pipeline.
2//!
3//! Set `DOCLING_RS_TIMING=1` to accumulate wall-clock time per named stage
4//! across all pages and print a sorted breakdown at process exit. Zero cost
5//! when the env var is unset (the `Instant` is still taken but nothing is
6//! recorded — call sites guard the hot path themselves where it matters).
7//!
8//! The totals are process-wide and cumulative ([`report`] prints them after
9//! every conversion). An embedder profiling one document at a time reads
10//! them with [`snapshot`] and clears them with [`reset`] (#897) instead of
11//! parsing stderr.
12
13use std::collections::BTreeMap;
14use std::sync::{Mutex, OnceLock};
15use std::time::Instant;
16
17pub(crate) fn enabled() -> bool {
18    static ON: OnceLock<bool> = OnceLock::new();
19    *ON.get_or_init(|| docling_core::env::flag("DOCLING_RS_TIMING"))
20}
21
22fn store() -> &'static Mutex<BTreeMap<&'static str, (u128, u64)>> {
23    static S: OnceLock<Mutex<BTreeMap<&'static str, (u128, u64)>>> = OnceLock::new();
24    S.get_or_init(|| Mutex::new(BTreeMap::new()))
25}
26
27/// Record `elapsed` nanoseconds against `stage`. No-op unless timing is enabled.
28pub fn record(stage: &'static str, nanos: u128) {
29    if !enabled() {
30        return;
31    }
32    let mut g = store().lock().unwrap();
33    let e = g.entry(stage).or_insert((0, 0));
34    e.0 += nanos;
35    e.1 += 1;
36}
37
38/// Time a closure and attribute its wall-clock to `stage`.
39pub fn timed<T>(stage: &'static str, f: impl FnOnce() -> T) -> T {
40    if !enabled() {
41        return f();
42    }
43    let t = Instant::now();
44    let out = f();
45    record(stage, t.elapsed().as_nanos());
46    out
47}
48
49/// Print the accumulated breakdown (descending by total time). Call once at the
50/// end of a conversion. No-op unless timing is enabled.
51pub fn report() {
52    if !enabled() {
53        return;
54    }
55    let g = store().lock().unwrap();
56    let mut rows: Vec<_> = g.iter().map(|(k, v)| (*k, v.0, v.1)).collect();
57    rows.sort_by_key(|r| std::cmp::Reverse(r.1));
58    let total: u128 = rows.iter().map(|r| r.1).sum();
59    eprintln!("=== DOCLING_RS timing (per stage, wall-clock) ===");
60    for (stage, nanos, calls) in &rows {
61        let ms = *nanos as f64 / 1e6;
62        let pct = if total > 0 {
63            *nanos as f64 / total as f64 * 100.0
64        } else {
65            0.0
66        };
67        eprintln!("  {stage:<22} {ms:>9.1} ms  {pct:>5.1}%  ({calls} calls)");
68    }
69    eprintln!("  {:<22} {:>9.1} ms", "TOTAL (summed)", total as f64 / 1e6);
70}
71
72/// One stage's accumulated time, as [`snapshot`] returns it.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct StageTiming {
75    /// The stage name (`layout.predict`, `render.page`, `tableformer`, …).
76    pub stage: &'static str,
77    /// Wall-clock time summed over every call (stages on parallel threads
78    /// overlap, so the totals can exceed the conversion's wall time).
79    pub total: std::time::Duration,
80    /// How many times the stage ran.
81    pub calls: u64,
82}
83
84/// The stages accumulated since the process started or the last [`reset`],
85/// longest first. Empty unless `DOCLING_RS_TIMING` is set.
86pub fn snapshot() -> Vec<StageTiming> {
87    let g = store().lock().unwrap_or_else(|p| p.into_inner());
88    let mut rows: Vec<StageTiming> = g
89        .iter()
90        .map(|(stage, (nanos, calls))| StageTiming {
91            stage,
92            total: std::time::Duration::from_nanos(u64::try_from(*nanos).unwrap_or(u64::MAX)),
93            calls: *calls,
94        })
95        .collect();
96    rows.sort_by_key(|r| std::cmp::Reverse(r.total));
97    rows
98}
99
100/// Forget the accumulated stages — e.g. between documents, so the next
101/// [`snapshot`] (and [`report`]) covers one conversion.
102pub fn reset() {
103    store().lock().unwrap_or_else(|p| p.into_inner()).clear();
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109
110    #[test]
111    fn snapshot_and_reset() {
112        // Recording is gated on DOCLING_RS_TIMING, read once per process:
113        // the shape is checked either way, the values when it is on.
114        reset();
115        record("test.stage", 2_000_000);
116        record("test.stage", 1_000_000);
117        let rows = snapshot();
118        if enabled() {
119            let row = rows.iter().find(|r| r.stage == "test.stage").unwrap();
120            assert_eq!((row.total.as_nanos(), row.calls), (3_000_000, 2));
121        } else {
122            assert!(rows.is_empty());
123        }
124        reset();
125        assert!(snapshot().iter().all(|r| r.stage != "test.stage"));
126    }
127}