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

^^^^^^^^ 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()
}

Leave a Reply