Instant Measures Monotonic Elapsed Time

Measure wall-clock work with Instant::now and elapsed, and rely on Instant's monotonic guarantee so later reads never precede earlier ones.

RustResilience

Code

rustsnippet
25 lines
use std::hint::black_box;
use std::time::{Duration, Instant};

fn simulate_batch(items: u64) {
    // 纯计算,给计时一个真实 workload
    let mut acc: u64 = 0;
    for i in 0..items {
        acc = acc.wrapping_add(i.wrapping_mul(i));
    }
    black_box(acc);
}

fn main() {
    let start = Instant::now();
    simulate_batch(1_000_000);
    let elapsed = start.elapsed();

    // Instant 是单调时钟:两次 now() 的差值不受系统时间调整影响
    let later = Instant::now();
    println!("elapsed: {} ms", elapsed.as_millis());

    let gap: Duration = later - start;
    println!("gap: {} us", gap.as_micros());
    println!("later >= start: {}", later >= start);
}

What the code does

The load-bearing code sits in the functions simulate_batch and main.

for i in 0..items is the loop that carries the per-item work.

What to watch for

  • No dependencies to install — the runtime already ships each API used here.

Using it

The primary signature is fn simulate_batch(items: u64)

The run emits 3 labeled sections — elapsed:, gap:, later >= start: — one per step.

The entry point wires simulate_batch together — run it once and the whole demo flows.

Key statements

fn simulate_batch(items: u64) {
    // 纯计算,给计时一个真实 workload
    let mut acc: u64 = 0;
    for i in 0..items {
        acc = acc.wrapping_add(i.wrapping_mul(i));
    }
    black_box(acc);
}

Interactive Tools for This Topic

FAQ

What does Instant Measures Monotonic Elapsed Time print when run?
Run it as a complete program — the output lines carry labels such as `elapsed:`, `gap:`, `later >= start:`.