Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust function returning std::time::Instant

I have a function that returns time elapsed.

I had originally tried

fn insert_test(Table: &mut HashMap<String,String>, items: &Vec<String>) -> std::time::Instant {

But the compiler errored on

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

^^^^^^^^ expected struct `Instant`, found `u128`

But the compiler tells me to use u128 instead

But how would I know u128 ahead of time? https://doc.rust-lang.org/std/time/struct.Instant.html itself does not explicitly state its of type u128

// inserts items onto the referenced datastruct and returns time elapsed
fn insert_test(Table: &mut HashMap<String,String>, items: &Vec<String>) -> u128 {
    let t0 = Instant::now();
    for i in items {
        Table.insert(i.to_string(), "blahblah".to_string());
    }
    let duration = t0.elapsed().as_millis();
    duration
}

rust playground link

>Solution :

Your instinct to return a time object rather than a raw number was a good one. However, time elapsed is better represented as a Duration (time delta) rather than an Instant (moment in time).

Instead of changing the return type I would remove the as_millis call. It works out nicely because elapsed returns a Duration, which is just what we want.

fn insert_test(Table: &mut HashMap<String, String>, items: &Vec<String>) -> std::time::Duration {
    let t0 = Instant::now();
    for i in items {
        Table.insert(i.to_string(), "blahblah".to_string());
    }
    t0.elapsed()
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading