Noob question about the .elapsed() function in the std::time::duration module

Hi, I am very new to rust, and I recently built a program that would time how long it takes to run through a loop a certain amount of times. I want to be able to add the elapsed time it took to run the loop to another variable to make a sum of all the time it took to run the loop multiple times. However, I cannot add the type std::time::Duration to another variable with the type u128. How can I convert std::time::Duration to u128?

If you want to add it to a u128, you need to decide on what unit you're counting. If milliseconds are enough precision for you, you could use duration.to_millis() to get a u128 and add that. (Or to_nanos if you need that.)

But I'd probably add it to a variable of type Duration, since you can add those together without losing the unit information. e.g.

let mut total_time = Duration::default();
for thingy in stuff_to_time {
    let start = Instant::now();
    total_time += start.elapsed();
println!("That took {:?}", total_time);

Ah, ok. That works great! thank you!

BTW, if you're benchmarking, try using Bencher instead:

because it's too easy to get noisy and misleading results with simple applicaiton of .elapsed().