Java에서와 같이 현재 시간을 밀리 초 단위로 어떻게 얻을 수 있습니까?
System.currentTimeMillis()
답변
Rust 1.8부터는 상자를 사용할 필요가 없습니다. 대신 사용할 수 있습니다 SystemTime및 UNIX_EPOCH:
use std::time::{SystemTime, UNIX_EPOCH};
fn main() {
    let start = SystemTime::now();
    let since_the_epoch = start
        .duration_since(UNIX_EPOCH)
        .expect("Time went backwards");
    println!("{:?}", since_the_epoch);
}
정확히 밀리 초가 필요한 경우 Duration.
녹 1.33
let in_ms = since_the_epoch.as_millis();
러스트 1.27
let in_ms = since_the_epoch.as_secs() as u128 * 1000 +
            since_the_epoch.subsec_millis() as u128;
러스트 1.8
let in_ms = since_the_epoch.as_secs() * 1000 +
            since_the_epoch.subsec_nanos() as u64 / 1_000_000;
답변
밀리 초로 간단한 타이밍을 수행하려면 다음 std::time::Instant과 같이 사용할 수 있습니다 .
use std::time::Instant;
fn main() {
    let start = Instant::now();
    // do stuff
    let elapsed = start.elapsed();
    // Debug format
    println!("Debug: {:?}", elapsed);
    // Format as milliseconds rounded down
    // Since Rust 1.33:
    println!("Millis: {} ms", elapsed.as_millis());
    // Before Rust 1.33:
    println!("Millis: {} ms",
             (elapsed.as_secs() * 1_000) + (elapsed.subsec_nanos() / 1_000_000) as u64);
}
산출:
Debug: 10.93993ms
Millis: 10 ms
Millis: 10 ms
답변
답변
답변
extern crate time;
fn timestamp() -> f64 {
    let timespec = time::get_time();
    // 1459440009.113178
    let mills: f64 = timespec.sec as f64 + (timespec.nsec as f64 / 1000.0 / 1000.0 / 1000.0);
    mills
}
fn main() {
    let ts = timestamp();
    println!("Time Stamp: {:?}", ts);
}
답변
System.currentTimeMillis() Java에서는 현재 시간과 1970 년 1 월 1 일 자정 사이의 차이 (밀리 초)를 반환합니다.
Rust에서는 1970 년 1 월 1 일 자정 이후 현재 시간을 초로, 오프셋을 나노초 단위로 time::get_time()반환하는 a Timespec를 가지고 있습니다 .
예 (Rust 1.13 사용) :
extern crate time; //Time library
fn main() {
    //Get current time
    let current_time = time::get_time();
    //Print results
    println!("Time in seconds {}\nOffset in nanoseconds {}",
             current_time.sec,
             current_time.nsec);
    //Calculate milliseconds
    let milliseconds = (current_time.sec as i64 * 1000) +
                       (current_time.nsec as i64 / 1000 / 1000);
    println!("System.currentTimeMillis(): {}", milliseconds);
}