DEVFYI - Developer Resource - FYI

Give a simplest way to find out the time a method takes for execution without using any profiling tool?

Java Interview Questions and Answers (part 3)


(Continued from previous question...)

509. Give a simplest way to find out the time a method takes for execution without using any profiling tool?

Read the system time just before the method is invoked and immediately after method returns. Take the time difference, which will give you the time taken by a method for execution.

To put it in code...
long start = System.currentTimeMillis ();
method ();
long end = System.currentTimeMillis ();

System.out.println ("Time taken for execution is " + (end - start));

Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds for execution. Try it on a method which is big enough, in the sense the one which is doing considerable amout of processing.

(Continued on next question...)

Other Interview Questions