rand_jitter/
platform.rs

1// Copyright 2018 Developers of the Rand project.
2// Copyright 2013-2015 The Rust Project Developers.
3//
4// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
7// option. This file may not be copied, modified, or distributed
8// except according to those terms.
9
10#[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "windows")))]
11pub fn get_nstime() -> u64 {
12    use std::time::{SystemTime, UNIX_EPOCH};
13
14    let dur = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
15    // The correct way to calculate the current time is
16    // `dur.as_secs() * 1_000_000_000 + dur.subsec_nanos() as u64`
17    // But this is faster, and the difference in terms of entropy is
18    // negligible (log2(10^9) == 29.9).
19    dur.as_secs() << 30 | dur.subsec_nanos() as u64
20}
21
22#[cfg(any(target_os = "macos", target_os = "ios"))]
23pub fn get_nstime() -> u64 {
24    use libc;
25    
26    // On Mac OS and iOS std::time::SystemTime only has 1000ns resolution.
27    // We use `mach_absolute_time` instead. This provides a CPU dependent
28    // unit, to get real nanoseconds the result should by multiplied by
29    // numer/denom from `mach_timebase_info`.
30    // But we are not interested in the exact nanoseconds, just entropy. So
31    // we use the raw result.
32    unsafe { libc::mach_absolute_time() }
33}
34
35#[cfg(target_os = "windows")]
36pub fn get_nstime() -> u64 {
37    use winapi;
38
39    unsafe {
40        let mut t = super::mem::zeroed();
41        winapi::um::profileapi::QueryPerformanceCounter(&mut t);
42        *t.QuadPart() as u64
43    }
44}