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.

RustData Fetching

Code

rustsnippet
25 lines
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

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:`.