Skip to content

Commit 7a066f8

Browse files
authored
Merge pull request eugenp#3955 from iaforek/master
BAEL-1648 - Measure Time Elapsed in Java
2 parents dca0a7c + 97c4058 commit 7a066f8

1 file changed

Lines changed: 76 additions & 0 deletions

File tree

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package com.baeldung.time;
2+
3+
import static org.junit.Assert.assertEquals;
4+
5+
import java.time.Duration;
6+
import java.time.Instant;
7+
import java.util.concurrent.TimeUnit;
8+
9+
import org.apache.commons.lang3.time.StopWatch;
10+
import org.junit.Test;
11+
12+
public class ElapsedTimeUnitTest {
13+
14+
@Test
15+
public void givenRunningTask_whenMeasuringTimeWithCurrentTimeMillis_thenGetElapsedTime() throws InterruptedException {
16+
long start = System.currentTimeMillis();
17+
18+
simulateRunningTask();
19+
20+
long finish = System.currentTimeMillis();
21+
22+
long timeElapsed = finish - start;
23+
24+
assertEquals(true, (2000L <= timeElapsed) && (timeElapsed <= 3000L));
25+
}
26+
27+
@Test
28+
public void giveRunningTask_whenMeasuringTimeWithNanoTime_thenGetElapsedTime() throws InterruptedException {
29+
long start = System.nanoTime();
30+
31+
simulateRunningTask();
32+
33+
long finish = System.nanoTime();
34+
35+
long timeElapsed = finish - start;
36+
37+
assertEquals(true, (2000000000L <= timeElapsed) && (timeElapsed <= 3000000000L));
38+
}
39+
40+
@Test
41+
public void givenRunningTask_whenMeasuringTimeWithStopWatch_thenGetElapsedTime() throws InterruptedException {
42+
StopWatch watch = new StopWatch();
43+
watch.start();
44+
45+
simulateRunningTask();
46+
47+
watch.stop();
48+
49+
long timeElapsed = watch.getTime();
50+
51+
assertEquals(true, (2000L <= timeElapsed) && (timeElapsed <= 3000L));
52+
}
53+
54+
@Test
55+
public void givenRunningTask_whenMeasuringTimeWithInstantClass_thenGetElapsedTime() throws InterruptedException {
56+
Instant start = Instant.now();
57+
58+
simulateRunningTask();
59+
60+
Instant finish = Instant.now();
61+
62+
long timeElapsed = Duration.between(start, finish).toMillis();
63+
64+
assertEquals(true, (2000L <= timeElapsed) && (timeElapsed <= 3000L));
65+
}
66+
67+
/**
68+
* Simulate task running for 2.5 seconds.
69+
*
70+
* @throws InterruptedException
71+
*/
72+
private static void simulateRunningTask() throws InterruptedException {
73+
TimeUnit.MILLISECONDS.sleep(2500); // 2.5 seconds
74+
75+
}
76+
}

0 commit comments

Comments
 (0)