1

I want to calculate the average time taken to call a method, but the results are very much dependent on the "numberOfTries" variable in the code below:

int averageExecutionTime = 0;
int numberOfTries = someNumber;

for(int i=0 ; i<numberOfTries ; ++i){
    long t = System.nanoTime();
    CallSomeMethod();
    averageExecutionTime += (System.nanoTime()-t);
}
averageExecutionTime /= numberOfTries;
System.out.println(averageExecutionTime);

When I run my method for the first time, it takes about 6000 nanoseconds to call the method. However, when I call it again, the time taken reduces to about 50 nanoseconds. What is the cause of this reduction?

Talendar
  • 1,841
  • 14
  • 23
user8733070
  • 31
  • 1
  • 4

1 Answers1

1

Likely the JIT (just-in-time) compiler. The JIT compiler can optimize your bytecode on-the-fly by detecting sub-optimal but recurrent execution patterns (and I'm guessing a lot of other things that I'm not aware about). That's why all benchmarks have a "warm-up" period before they start measuring the performance: it takes some time for a Java program to reach its peak performance after some cycles of JIT optimization.

Just as an experiment, try skipping the first 50 executions of your methods and see if there's a difference. If there isn't, try with 100 and so on.

As pointed out by Eugene, a more robust way to perform benchmark is to use a library designed by people who have thought all of this through. jmh is one such library.

Dici
  • 25,226
  • 7
  • 41
  • 82
  • while you may be right, a better answer would be to suggest a library that will handle that, because there are only a few people here on SO that can trully tell you exactly what is going on in these examples; a simpler way is to use a micro benchmark library, like `jmh` – Eugene Sep 09 '18 at 20:30
  • I think a better answer would do both of these things. An answer simply recommending a library would prevent the OP from getting curious about what mechanisms in the JVM might explain what they're seeing, and that these mechanisms even exist. – Dici Sep 09 '18 at 20:34
  • agreed; just that "these details" will suck up the life out of you, though they are interesting – Eugene Sep 09 '18 at 20:37