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.
Code
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
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.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.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 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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.