Friday, July 28, 2017

Java - Calculate Total Time Elapsed using Java5 or higher



Java - How to calculate the total Time elapsed for a java method.

It is a standard requirement in a lot Java components/applications to find out the total time a method has taken to execute the call.

Though there are several 3rd party libraries (Spring MethodInterceptor,  java-InvocationHandler/DynamicProxy, and AspectOrientedProgramming) that offer method interceptor feature where the time can can be tracked.
Looking at greater need of this requirement of calculating precise time (NanoSeconds..) that a method spent on, Java5 has introduced a new TimeUnit class.

Please see below example for reference

public static String calculateTotalTimeElapsed(long startNanoSec, long endNanoSec) {
long difference = endNanoSec - startNanoSec;
String totalTimeString = String.format("%d Hours, %d Min, %d Sec, %d Millis, %d Micro, %d Nano",
TimeUnit.NANOSECONDS.toHours(difference), TimeUnit.NANOSECONDS.toMinutes(difference),
TimeUnit.NANOSECONDS.toSeconds(difference), TimeUnit.NANOSECONDS.toMillis(difference),
TimeUnit.NANOSECONDS.toMicros(difference), TimeUnit.NANOSECONDS.toNanos(difference));
return totalTimeString;
}


       public static void main(String args[]){ 
               long timeBefore1 = System.nanoTime();
               //TODO: call any other function (db or resource intensive)
               String timeString = calculateTotalTimeElapsed(timeBefore1, System.nanoTime());
              System.out.println("Method has taken  "+timeString);
       }
     

output:
o Hours, 1 Min, 2 Sec, 400 Millis, 298 Micro, 12345 Nano.