Beyond System.currentTimeMillis: Measuring Time with Duration and Instant

With Duration and Instant classes, introduced in Java 8, you can calculate time spent in methods:

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

public class DurationTest {

    public void durationInSecondsAndMillis() throws InterruptedException{
        var start =;
        var duration = Duration.between(start,;
        System.out.printf("%d seconds and %d ms",duration.toSeconds(),duration.toMillisPart());

The test above writes the following output: 2 seconds and 43 ms


Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
...the last 150 posts
...the last 10 comments