Rust : time,关于程序运行的计时

一、系统自带的包,time
有两种方式:都可以;缺点是,目前只有as_secs().
目前 as_millis() 还处于nightly阶段,后续才会推出。

use std::time::{Duration, SystemTime};
fn fib(x: i64) -> i64 {
    match x <2{
        true => x,
        _ => fib(x - 2) + fib(x - 1),
    }
}
fn main() {
    let nums:Vec = vec![30_i64,35,40,45];
    for n in nums {
        let sy_time = SystemTime::now();
        let value = fib(n);
        println!("{:?},{:?}", SystemTime::now().duration_since(sy_time).unwrap().as_secs(),value);
        println!("{:?},{:?}", sy_time.elapsed().unwrap().as_secs(),value);
    }
    thread::sleep_ms(500000);
}

期待nightly升级…
Rust : time,关于程序运行的计时_第1张图片
二、外部的包,stopwatch=“0.0.7”

优点:精度高。

extern crate stopwatch;
use stopwatch::{Stopwatch};

fn fib(x: i64) -> i64 {
    match x <2{
        true => x,
        _ => fib(x - 2) + fib(x - 1),
    }
}

fn main() {
    let nums:Vec = vec![30_i64,35,40,45];
    for n in nums {
        let sw = Stopwatch::start_new();
        let value = fib(n);
        println!("n:{0} recur value :{1} It took {2:.8} ms",n,value,sw.elapsed_ms());
    }

三、使用 time库

这里用到了time库,这个库已经不再更新了,后面会转移到chrono中。

time = "0.1"
//extern crate chrono; //0.4
extern crate time; //0.1 
//use chrono::prelude::*;
use std::thread;
use time::*;

fn fib(x: i64) -> i64 {
    match x < 2 {
        true => x,
        _ => fib(x - 2) + fib(x - 1),
    }
}
fn main() {
    let start = time::now(); //获取开始时间
    let nums: Vec = vec![30_i64, 35, 40, 45];
    for n in nums {
        let value = fib(n);
    }
    let end = time::now(); //获取结束时间
    println!(
        "done!start : {:?},end :{:?},duration:{:?}",
        start,
        end,
        end - start
    );
    thread::sleep_ms(500000);
}

你可能感兴趣的:(Rust)