-1

Possible Duplicate:
How do I time a method's execution in Java?

I would like to know what the code would be to find how much time a function takes to execute till its last statement starting from the first.Suppose my function is like this:

public void sum(int a,int b)
{
    int c;
    c=a+b;
    System.out.print(c);
}

Please insert the necessary code into the above function itself. Will be very helpful.

Community
  • 1
  • 1
Jeris
  • 2,355
  • 4
  • 26
  • 38
  • Measuring a single call to this function will be extremely unreliable. In general, you need to run this e.g. 1 million times, measure the time taken, and then divide by 1 million. – Oliver Charlesworth Sep 09 '11 at 14:07
  • “Here, please do my work for me!” — No way. – Bombe Sep 09 '11 at 14:08
  • Writing to IO is thousands of times more expensive than every else this method is doing. The time the IO takes depends on how it is displayed e.g. in an IDE, DOS window or redirected to a file will get very different results. – Peter Lawrey Sep 09 '11 at 15:06

1 Answers1

0
public static void sum(int a, int b) {
    long startTime = System.nanoTime();
    int c;
    c = a + b;
    System.out.println(c);
    System.out.println("Time taken (in ms)= "+
                       (System.nanoTime() - startTime) / 1E6);
}
Sahil Muthoo
  • 12,033
  • 2
  • 29
  • 38