I am reading the system time just before the method is invoked and immediately after method returns and taking the time difference, which will give the time taken by a method for execution.
Code snippet
long start = System.currentTimeMillis ();
method ();
long end = System.currentTimeMillis ();
System.out.println ("Time taken for execution is " + (end - start));
The strange thing is the output is 0..how is this possible..?
Chances are it’s taking a shorter time than the fairly coarse-grained system clock. (For example, you may find that
System.currentTimeMillis()only changes every 10 or 15 milliseconds.)System.currentTimeMillisis good for finding out the current time, but it’s not fine-grained enough for measuring short durations. Instead, you should useSystem.nanoTime()which uses a high-resolution timer.nanoTime()is not suitable for finding the current time – but it’s designed for measuring durations.Think of it as being the difference between a wall clock and a stopwatch.