Easiest Way to calculate elapsed time in Java

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

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.

Leave a Reply

Your email address will not be published. Required fields are marked *