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.
Code
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
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 Difference CalculatorCalculate the number of days, weeks, whole months, and years between two ISO dates, computed in UTC.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.