Sum Durations With Iterator Sum

Duration implements Sum, so one iterator pass adds step timings; dividing by the step count with Div<u32> yields the average without a manual loop.

RustData Integrity

Code

rustsnippet
18 lines
use std::time::Duration;

fn main() {
    let steps = [
        Duration::from_millis(120),
        Duration::from_millis(80),
        Duration::from_millis(250),
    ];

    // Duration 实现了 Sum:一次遍历得到总耗时
    let total: Duration = steps.iter().sum();
    println!("total: {total:?}");
    println!("millis: {}", total.as_millis());

    // Div<u32> 也实现了:平均值一行算完
    let average = total / steps.len() as u32;
    println!("average: {average:?}");
}

What the code does

The moving parts are the function main.

Caveats

  • The imports (if any) point only at standard-library modules.

Using it

Signature: fn main()

Running the file prints labeled results such as total:, millis:, average: — each operation’s effect is visible in the output.

Key statements

let total: Duration = steps.iter().sum();

Interactive Tools for This Topic

FAQ

What does Sum Durations With Iterator Sum print when run?
Run it as a complete program — the output lines carry labels such as `total:`, `millis:`, `average:`.