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.
Code
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
Date Difference CalculatorCalculate the number of days, weeks, whole months, and years between two ISO dates, computed in UTC.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.ISO 8601 Duration ParserParse ISO 8601 durations like PT1H30M into year, month, week, day, and time components with exact or approximate total seconds.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.