Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Find Time Difference using Chrono library in Rust

Tags:

time

rust

I have a Rust program where I want to do some simple benchmarking with start time and end time!

use chrono::{NaiveTime, Utc};

fn main() {
    let start_time: NaiveTime = Utc::now().time();
    let end_time: NaiveTime = Utc::now().time();
    println!("Total time taken to run is {}", end_time - start_time);
}

The code above prints as:

Total time taken to run is PT520.532696S

I guess it is 520 seconds if I'm not wrong, but how can I convert that into minutes? Is there a better way?

like image 376
joesan Avatar asked Jan 27 '23 06:01

joesan


1 Answers

A simple look to the doc give the answer:

use chrono::Utc;

fn main() {
    let start_time = Utc::now().time();
    let end_time = Utc::now().time();
    let diff = end_time - start_time;
    println!("Total time taken to run is {}", diff.num_minutes());
}

but be aware that it's not a good way to mesure time in a monotonic way, this code could show -5 minutes if user change the system date somehow. Also call time() remove the information of the date, and this is strange when you use chrono because generally you don't want to ignore the date so just remove time() call.

like image 129
Stargateur Avatar answered Jan 29 '23 07:01

Stargateur