Calculate elapsed time

Elapsed time is the time or difference between a beginning time and an ending time. This example will show how to find the elapsed time between two dates using System.currentTimeMillis, System.nanoTime(), guava Stopwatch, apache commons stopwatch and spring framework’s stopwatch classes. Finding elapsed time is important to test method execution times and various other peformance related measures.

Straight up Java

System.currentTimeMillis()

@Test
public void calculate_elapsed_time_in_java ()
    throws InterruptedException {

    long startTime = System.currentTimeMillis();

    Thread.sleep(2); // simulate work

    long estimatedTime = System.currentTimeMillis() - startTime;

    logger.info("time: " + estimatedTime);

    assertTrue(estimatedTime >= 0);
}

System.nanoTime()

@Test
public void calculate_elapsed_time_nano_in_java ()
    throws InterruptedException {

    long startTime = System.nanoTime();

    Thread.sleep(2); // simulate work

    long estimatedTime = System.nanoTime() - startTime;

    logger.info("time: " + estimatedTime);

    assertTrue(estimatedTime >= 0);
}

Google Guava

@Test
public void calculate_elapsed_time_in_guava()
    throws InterruptedException {

    Stopwatch stopwatch = Stopwatch.createStarted();

    Thread.sleep(2); // simulate work

    stopwatch.stop(); // optional

    long millis = stopwatch.elapsed(TimeUnit.MILLISECONDS);

    logger.info("time: " + stopwatch);

    assertTrue(millis >= 0);
}

Apache Commons

@Test
public void calculate_elapsed_time_in_apache_commons ()
    throws InterruptedException {

    StopWatch stopWatch = new StopWatch();
    stopWatch.start();

    Thread.sleep(2); // simulate work

    stopWatch.stop();
    long millis = stopWatch.getNanoTime();

    logger.info("time: " + millis);

    assertTrue(millis >= 0);
}

Spring Framework

@Test
public void calculate_elapsed_time_in_spring () throws InterruptedException {

    org.springframework.util.StopWatch stopWatch =
            new org.springframework.util.StopWatch();

    stopWatch.start("step 1");
    Thread.sleep(2); // simulate work
    stopWatch.stop();

    stopWatch.start("step 2");
    Thread.sleep(5); // simulate work
    stopWatch.stop();

    stopWatch.start("step 3");
    Thread.sleep(3); // simulate work
    stopWatch.stop();

    logger.info("time: " + stopWatch.prettyPrint());

    assertTrue(stopWatch.getTotalTimeMillis() >= 0);
}

Output

time: StopWatch '': running time (millis) = 11
-----------------------------------------
ms     %     Task name
-----------------------------------------
00002  018%  step 1
00006  055%  step 2
00003  027%  step 3