zParacha.

Effective Programming Tips

← Home

Easiest way to calculate elapsed time in Java

December 23, 2017

Quite often in our day-to-day programming, we need to compute how long a specific portion of the code takes to complete. For e.g; you might want to check how long a method takes to complete. In Java, the simplest way to accomplish this is to use System.nanoTime() method.

The following example shows how you can do it.

long startTime = System.nanoTime();
System.out.println("Random string = " + getRandomAlphNumeircString(n));
long endTime = System.nanoTime();
double runTime = (endTime - startTime) / 1_000_000_000.0;
NumberFormat formatter = new DecimalFormat("#00.0000000000000000");
System.out.println("Run time = " + formatter.format(runTime));

Before calling the method for which we want to measure the execution time we record the current time in a local variable (startTime), we then call the method. After the method is complete we call System.nanoTime() to get the current time again. To find the elapsed time we subtract startTime from endTime and divide the result by 1 billion (to convert nanoseconds into seconds).

To display the elapsed time in a more readable format we used NumberFormat class, otherwise, since the values will be too small you will get the result in scientific notation.

A more readable option: java.time.Duration

System.nanoTime() is still the right tool for measuring elapsed time — it isn’t affected by wall-clock adjustments the way System.currentTimeMillis() is. But rather than hand-rolling the formatting, Duration (Java 8+) can turn the raw nanoseconds into something readable on its own:

long startTime = System.nanoTime();
System.out.println("Random string = " + getRandomAlphNumeircString(n));
long endTime = System.nanoTime();

Duration elapsed = Duration.ofNanos(endTime - startTime);
System.out.println("Run time = " + elapsed.toMillis() + " ms");

This is unchanged on JDK 21 and avoids pulling in NumberFormat/DecimalFormat just to print a duration.