1

I am trying to test some queue insertions and removal of objects timestamp. After a few test runs I have a significant speedup improvement of upto 80 times better results on the same code. This looks clearly a caching result either by JVM or the hardware\cpu cache, but I wish to get fresh results each run.

Is there a way to clear both\either of these caches programmatically from within the Java code?

assylias
  • 321,522
  • 82
  • 660
  • 783
shaydel
  • 589
  • 4
  • 15

2 Answers2

6

This is probably due to the JIT kicking in. The JIT will compile your bytecode to machine code after a certain number of runs to make it more efficient.

You can change the number of calls before a method gets optimised by setting the -XX:CompileThreshold option (default value is 10,000) or by excluding your class from being optimised at all.

However I'm not sure why you would want to disable the compiler and force your program to run more slowly.

Community
  • 1
  • 1
assylias
  • 321,522
  • 82
  • 660
  • 783
  • 2
    Or he could turn the JIT compiler off completely ... though doing these means he will measure the code running in an unrealistic way. The numbers may not be indicative of real performance. – Stephen C Feb 17 '13 at 08:15
0

If you want to design a microbenchmark, I would suggest using JMH.

It is 'the' microbenchmarking framework and it will take care of JIT warmup, dead code elimination etc. It also has out of the box support for various profilers including Linux Perf.

https://www.baeldung.com/java-microbenchmark-harness

https://github.com/openjdk/jmh

pveentjer
  • 10,545
  • 3
  • 23
  • 40