Skip to content

Use CLOCK_MONOTONIC_COARSE in libnative on linux. #11981

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions src/libnative/io/timer_other.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ pub enum Req {
}

// returns the current time (in milliseconds)
#[cfg(not(target_os = "linux"))]
fn now() -> u64 {
unsafe {
let mut now: libc::timeval = intrinsics::init();
Expand All @@ -93,6 +94,42 @@ fn now() -> u64 {
}
}

// Use CLOCK_MONOTONIC_COARSE when available (Linux >= 2.6.32) and accurate
// enough for millisecond resolution, else fall back to CLOCK_MONOTONIC.
// The coarse clock uses the vDSO and skips the system call entirely.
// FIXME(bnoordhuis) Not safe to enable on Android because old versions
// of the NDK don't have clock_getres() and clock_gettime(). It should
// be possible to work around that using weak linking but that requires
// weak symbol support first. (Either that or by parsing the auxiliary
// vector at start-up and looking up the vDSO from there.)
#[cfg(target_os = "linux")]
fn now() -> u64 {
use std::sync::atomics::{INIT_ATOMIC_INT, AtomicInt, SeqCst};
use std::unstable::intrinsics;

extern {
fn clock_getres(_: libc::c_int, _: *mut libc::timespec) -> libc::c_int;
fn clock_gettime(_: libc::c_int, _: *mut libc::timespec) -> libc::c_int;
}

static mut clock_id: AtomicInt = INIT_ATOMIC_INT;
unsafe {
let mut ts: libc::timespec = intrinsics::uninit();
let mut id = clock_id.load(SeqCst) as libc::c_int;
// Note: this trick doesn't work for CLOCK_REALTIME, it has clock id 0.
if id == 0 {
let rc = clock_getres(CLOCK_MONOTONIC_COARSE, &mut ts);
id = match rc == 0 && ts.tv_sec == 0 && ts.tv_nsec <= 1_000_000 {
true => CLOCK_MONOTONIC_COARSE,
false => CLOCK_MONOTONIC,
};
clock_id.store(id as int, SeqCst);
}
assert_eq!(clock_gettime(id, &mut ts), 0);
ts.tv_sec as u64 * 1000 + ts.tv_nsec as u64 / 1_000_000
}
}

fn helper(input: libc::c_int, messages: Port<Req>) {
let mut set: imp::fd_set = unsafe { intrinsics::init() };

Expand Down