Skip to content

Commit

Permalink
For raw timestamps on macOS, use mach_absolute_time nanoseconds.
Browse files Browse the repository at this point in the history
  • Loading branch information
mstange committed Feb 8, 2024
1 parent f387ef0 commit 756e692
Showing 1 changed file with 18 additions and 6 deletions.
24 changes: 18 additions & 6 deletions samply/src/mac/time.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,20 @@
use mach::mach_time;
use once_cell::sync::OnceCell;

static NANOS_PER_TICK: OnceCell<mach_time::mach_timebase_info> = OnceCell::new();

pub fn get_monotonic_timestamp() -> u64 {
let mut ts = libc::timespec {
tv_sec: 0,
tv_nsec: 0,
};
unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts) };
ts.tv_sec as u64 * 1_000_000_000 + ts.tv_nsec as u64
let nanos_per_tick = NANOS_PER_TICK.get_or_init(|| unsafe {
let mut info = mach_time::mach_timebase_info::default();
let errno = mach_time::mach_timebase_info(&mut info as *mut _);
if errno != 0 || info.denom == 0 {
info.numer = 1;
info.denom = 1;
};
info
});

let time = unsafe { mach_time::mach_absolute_time() };

time * nanos_per_tick.numer as u64 / nanos_per_tick.denom as u64
}

0 comments on commit 756e692

Please sign in to comment.