0

I have a static method that consists of a nested loop going over an integer array of size 10,000. I call that method once, and measure the time using System.currentTimeMillis() (also measured with System.nanoTime()). I then call that method again and measure the time again. I am getting different time taken for both calls. The second call usually takes less time.

A slight difference is fine, but sometimes the difference is significant (more than 5 times the time taken to run the second call). E.g. first method call would take 190ms and the second call would only take 35ms. I have also tried pausing the thread in between the method calls, but the difference in time taken remains.

How can I have a stable measurement of time taken for a method call such that the time taken does not vary significantly for repeated calls?

SaadH
  • 1,158
  • 2
  • 23
  • 38
  • 2
    Java has a [JIT](https://en.wikipedia.org/wiki/Just-in-time_compilation). You should see [How do I write a correct micro-benchmark in Java?](https://stackoverflow.com/q/504103/2970947) – Elliott Frisch Jul 27 '19 at 00:57
  • The answers to the linked question are no more up to date. If you want a serious measurement, learn [JMH](https://openjdk.java.net/projects/code-tools/jmh/). Doing it manually is rather futile (unless you happily accept any nonsense figures) and other tools are AFAIK long obsolete. – maaartinus Jul 27 '19 at 02:59

0 Answers0