1

I was wondering if calculating a method's execution time this way is accurate:

public class GetExecutionTimes {

  public static void main(String args[]) {
    long startTime = System.currentTimeMillis();
    GetExecutionTimes ext = new GetExecutionTimes();
    ext.callMethod();
    long endTime = System.currentTimeMillis();
    System.out.println("Total elapsed time in execution of"
        + " method callMethod() is :" + (endTime - startTime));
  }

  public void callMethod() {
    System.out.println("Calling method");
    for (int i = 1; i <= 10; i++) {
      System.out.println("Value of counter is " + i);
    }
  }
}

More specifically: Will the time difference be the same if I execute in different conditions?

If not how can I make this calculate more precise?

Philipp Reichart
  • 20,771
  • 6
  • 58
  • 65
Mike G
  • 4,829
  • 11
  • 47
  • 76

2 Answers2

2

There are several aspects of Java that make writing micro-benchmarks difficult. Garbage collection and just-in-time compilation are two of them.

I would suggest the following as a very good starting point: How do I write a correct micro-benchmark in Java?

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

If you attempt to time only the method callMethod() you should move the constructor call before registering the start time.

You should also use nanoTime() rather then currentTimeMillis() since the letter is susceptible to errors due to changes in local clock (e.g. daylight saving time adjustments or someone on the machine simply changing the time).

The accuracy will depend on your platform and is not necessarily in the units the function names suggest.

Adam Zalcman
  • 26,643
  • 4
  • 71
  • 92