Skip to main content

psync/
profile.rs

1//! Traces for `psync-predict`, from functions annotated `#[psync::graph(profile)]`.
2//!
3//! Such a function runs as written, and reports every statement that awaits: its source line and
4//! how long it took, by the clock you install. Install a clock and a sink once, before the run:
5//!
6//! ```ignore
7//! fn clock() -> u64 { /* microseconds since some start */ }
8//! fn sink(line: usize, cost: u64) { println!("{line} {cost}") }
9//! psync::profile::install(clock, sink);
10//! ```
11//!
12//! Without them, profiled statements report nothing. A statement left by `?`, `return` or
13//! `break` reports nothing either, so trace a run that does not take an early exit.
14use core::sync::atomic::{AtomicPtr, Ordering};
15
16static CLOCK: AtomicPtr<()> = AtomicPtr::new(core::ptr::null_mut());
17static SINK: AtomicPtr<()> = AtomicPtr::new(core::ptr::null_mut());
18
19/// Use `clock` to time profiled statements and `sink` to receive each one's `(line, cost)`.
20pub fn install(clock: fn() -> u64, sink: fn(usize, u64)) {
21    CLOCK.store(clock as *mut (), Ordering::Release);
22    SINK.store(sink as *mut (), Ordering::Release);
23}
24
25pub(crate) fn now() -> Option<u64> {
26    let p = CLOCK.load(Ordering::Acquire);
27    // SAFETY: only `install` stores here, and only a `fn() -> u64`.
28    (!p.is_null()).then(|| unsafe { core::mem::transmute::<*mut (), fn() -> u64>(p) }())
29}
30
31pub(crate) fn record(line: usize, cost: u64) {
32    let p = SINK.load(Ordering::Acquire);
33    if !p.is_null() {
34        // SAFETY: only `install` stores here, and only a `fn(usize, u64)`.
35        let sink = unsafe { core::mem::transmute::<*mut (), fn(usize, u64)>(p) };
36        sink(line, cost);
37    }
38}