#![allow(
unsafe_code,
reason = "reviewed clock_gettime and native thread identity calls imported from Profiler"
)]
#[must_use]
#[allow(
clippy::cast_sign_loss,
reason = "successful native monotonic clocks have nonnegative seconds and nanoseconds"
)]
pub fn monotonic_ns() -> u64 {
static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
#[cfg(unix)]
{
let mut value = libc::timespec {
tv_sec: 0,
tv_nsec: 0,
};
if unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &raw mut value) } == 0 {
return (value.tv_sec as u64)
.saturating_mul(1_000_000_000)
.saturating_add(value.tv_nsec as u64);
}
}
u64::try_from(
START
.get_or_init(std::time::Instant::now)
.elapsed()
.as_nanos(),
)
.unwrap_or(u64::MAX)
}
#[must_use]
#[allow(
clippy::cast_sign_loss,
reason = "successful native CPU clocks have nonnegative seconds and nanoseconds"
)]
pub fn thread_cpu_ns() -> u64 {
#[cfg(unix)]
{
let mut value = libc::timespec {
tv_sec: 0,
tv_nsec: 0,
};
if unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &raw mut value) } == 0 {
return (value.tv_sec as u64)
.saturating_mul(1_000_000_000)
.saturating_add(value.tv_nsec as u64);
}
}
0
}
#[must_use]
pub fn tid() -> u64 {
#[cfg(target_os = "linux")]
{
u64::try_from(unsafe { libc::syscall(libc::SYS_gettid) }).unwrap_or_default()
}
#[cfg(target_os = "macos")]
{
let mut id = 0;
if unsafe { libc::pthread_threadid_np(0, &raw mut id) } == 0 {
id
} else {
0
}
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
{
0
}
}