Duration Math For Timeout Budgets
Duration arithmetic scales and splits timeout budgets, checked_add returns None on overflow, and min clamps a deadline under a hard cap.
Code
use std::time::Duration;
fn main() {
let per_request = Duration::from_millis(750);
let retries = 3u32;
// 乘法:整体预算 = 单次时长 × 次数
let budget = per_request * retries;
println!("budget: {} ms", budget.as_millis());
// checked 运算:溢出返回 None 而不是 panic
let huge = Duration::from_millis(u64::MAX);
println!("overflow: {:?}", per_request.checked_add(huge));
// 加余量后用 min 封顶:预算不超过硬上限
let cap = Duration::from_secs(5);
let with_margin = budget + Duration::from_millis(100);
println!("capped: {} ms", with_margin.min(cap).as_millis());
// 除法:把预算切成等长片段
println!("slice: {} ms", (budget / 5).as_millis());
// 浮点秒:指标上报常用单位
println!("secs: {:.2}", budget.as_secs_f64());
}What the code does
Duration Math For Timeout Budgets comes down to the function main.
Applying it
Running the file prints labeled results such as budget:, overflow:, capped: — each operation’s effect is visible in the output.
Statements that matter
let with_margin = budget + Duration::from_millis(100);
let per_request = Duration::from_millis(750);
let huge = Duration::from_millis(u64::MAX);
Interactive Tools for This Topic
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.Date Add/Subtract CalculatorAdd or subtract days, weeks, months, or years from a date, clamping month ends such as January 31 plus one month.
FAQ
- What does Duration Math For Timeout Budgets print when run?
- Execute the whole file; each printed line is prefixed with a label like `budget:`, `overflow:`, `capped:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.