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 {

    @Test
    public void durationInSecondsAndMillis() throws InterruptedException{
        var start = Instant.now();
        Thread.sleep(2042);
        var duration = Duration.between(start,Instant.now());
        System.out.printf("%d seconds and %d ms",duration.toSeconds(),duration.toMillisPart());
    }
}    

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

Comments:

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