From 97c405834eee35fb1a5c028d3e298782ec161a08 Mon Sep 17 00:00:00 2001 From: iaforek Date: Sun, 8 Apr 2018 15:48:13 +0100 Subject: [PATCH] BAEL-1648 - Measure Time Elapsed in Java --- .../baeldung/time/ElapsedTimeUnitTest.java | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 core-java-8/src/test/java/com/baeldung/time/ElapsedTimeUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/time/ElapsedTimeUnitTest.java b/core-java-8/src/test/java/com/baeldung/time/ElapsedTimeUnitTest.java new file mode 100644 index 0000000000..1d92684ef4 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/time/ElapsedTimeUnitTest.java @@ -0,0 +1,76 @@ +package com.baeldung.time; + +import static org.junit.Assert.assertEquals; + +import java.time.Duration; +import java.time.Instant; +import java.util.concurrent.TimeUnit; + +import org.apache.commons.lang3.time.StopWatch; +import org.junit.Test; + +public class ElapsedTimeUnitTest { + + @Test + public void givenRunningTask_whenMeasuringTimeWithCurrentTimeMillis_thenGetElapsedTime() throws InterruptedException { + long start = System.currentTimeMillis(); + + simulateRunningTask(); + + long finish = System.currentTimeMillis(); + + long timeElapsed = finish - start; + + assertEquals(true, (2000L <= timeElapsed) && (timeElapsed <= 3000L)); + } + + @Test + public void giveRunningTask_whenMeasuringTimeWithNanoTime_thenGetElapsedTime() throws InterruptedException { + long start = System.nanoTime(); + + simulateRunningTask(); + + long finish = System.nanoTime(); + + long timeElapsed = finish - start; + + assertEquals(true, (2000000000L <= timeElapsed) && (timeElapsed <= 3000000000L)); + } + + @Test + public void givenRunningTask_whenMeasuringTimeWithStopWatch_thenGetElapsedTime() throws InterruptedException { + StopWatch watch = new StopWatch(); + watch.start(); + + simulateRunningTask(); + + watch.stop(); + + long timeElapsed = watch.getTime(); + + assertEquals(true, (2000L <= timeElapsed) && (timeElapsed <= 3000L)); + } + + @Test + public void givenRunningTask_whenMeasuringTimeWithInstantClass_thenGetElapsedTime() throws InterruptedException { + Instant start = Instant.now(); + + simulateRunningTask(); + + Instant finish = Instant.now(); + + long timeElapsed = Duration.between(start, finish).toMillis(); + + assertEquals(true, (2000L <= timeElapsed) && (timeElapsed <= 3000L)); + } + + /** + * Simulate task running for 2.5 seconds. + * + * @throws InterruptedException + */ + private static void simulateRunningTask() throws InterruptedException { + TimeUnit.MILLISECONDS.sleep(2500); // 2.5 seconds + + } +}