From 756e6920051e1b6e3bdb55486ecba24cf643bab9 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Sat, 3 Jun 2023 09:23:28 -0400 Subject: [PATCH] For raw timestamps on macOS, use mach_absolute_time nanoseconds. --- samply/src/mac/time.rs | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/samply/src/mac/time.rs b/samply/src/mac/time.rs index 0c3a6f36..12032575 100644 --- a/samply/src/mac/time.rs +++ b/samply/src/mac/time.rs @@ -1,8 +1,20 @@ +use mach::mach_time; +use once_cell::sync::OnceCell; + +static NANOS_PER_TICK: OnceCell = 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 }