BAEL-1648 - Measure Time Elapsed in Java

This commit is contained in:
iaforek 2018-04-08 15:48:13 +01:00
parent 3d827783f7
commit 97c405834e
1 changed files with 76 additions and 0 deletions

View File

@ -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
}
}