Instant Duration Elapsed Time Measurement

Measure with Instant and Duration: capture the start, compare elapsed against a budget with compareTo, and report toMillis instead of hand-rolled math.

JavaResilience

Code

snippet
import java.time.Duration;
import java.time.Instant;

public class ElapsedTiming {

    static final Duration BUDGET = Duration.ofMillis(200);

    public static void main(String[] args) throws InterruptedException {
        Instant start = Instant.now();

        Thread.sleep(50);  // 被测操作

        Duration elapsed = Duration.between(start, Instant.now());
        System.out.println("elapsed ms: " + elapsed.toMillis());

        // compareTo 逐单位比较两个 Duration:50ms 预算内,超过才告警
        System.out.println("within budget: " + (elapsed.compareTo(BUDGET) <= 0));
        System.out.println("over budget:   " + (elapsed.compareTo(BUDGET) > 0));
    }
}

How it works

Count the class ElapsedTiming as the entire surface area of Instant Duration Elapsed Time Measurement.

Using it

Running the file prints labeled results such as elapsed ms:, within budget:, over budget: — each operation’s effect is visible in the output.

Key statements

Thread.sleep(50);  // 被测操作
Duration elapsed = Duration.between(start, Instant.now());

Interactive Tools for This Topic

FAQ

What does Instant Duration Elapsed Time Measurement print when run?
Invoke the file as-is — the `elapsed ms:`, `within budget:`, `over budget:` prefixes identify which step printed each line.