Merge pull request #3955 from iaforek/master

BAEL-1648 - Measure Time Elapsed in Java
This commit is contained in:
Tom Hombergs 2018-04-09 22:23:17 +02:00 committed by GitHub
commit 7a066f8952
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
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
}
}