Easiest way to calculate elapsed time in Java

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)/10000000000.0;
NumberFormat formatter = new DecimalFormat("#00.0000000000000000");
System.out.println("RumTIme = "+ 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.