light_tool/timestamp.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
use std::time::{SystemTime, UNIX_EPOCH};
/// Returns the current time in seconds
///
/// # Example
///
/// ```no_run
/// use light_tool::timestamp;
/// println!("second timestamp: {}", timestamp::seconds());
/// ```
pub fn seconds() -> u64 {
match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(n) => n.as_secs(),
Err(_) => panic!("SystemTime before UNIX EPOCH!"),
}
}
/// Returns the current time in milliseconds
///
/// # Example
///
/// ```no_run
/// use light_tool::timestamp;
/// println!("milli second timestamp: {}", timestamp::milli_seconds());
/// ```
pub fn milli_seconds() -> u64 {
match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(n) => n.as_millis() as u64,
Err(_) => panic!("SystemTime before UNIX EPOCH!"),
}
}
/// Returns the current time in nanoseconds
///
/// # Example
///
/// ```no_run
/// use light_tool::timestamp;
/// println!("nano second timestamp: {}", timestamp::nano_seconds());
/// ```
pub fn nano_seconds() -> u64 {
match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(n) => n.as_nanos() as u64,
Err(_) => panic!("SystemTime before UNIX EPOCH!"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_seconds() {
let seconds = seconds();
println!("seconds: {}", seconds);
assert!(seconds > 0);
}
#[test]
fn test_milli_seconds() {
let milli_seconds = milli_seconds();
println!("milli_seconds: {}", milli_seconds);
assert!(milli_seconds > 0);
}
#[test]
fn test_nano_seconds() {
let nano_seconds = nano_seconds();
println!("nano_seconds: {}", nano_seconds);
assert!(nano_seconds > 0);
}
}