Search code examples
scalaperformancejvmperformance-testingjit

Is it possible to disable JVM JIT loop optimisation


I have pretty trivial scala code:

  def main(): Int = {
    var i: Int = 0
    var limit = 0

    while (limit < 1000000000) {
      i = inc(i)
      limit = limit + 1
    }
    i
  }

  def inc(i: Int): Int = i + 1

I am playing with JVM JIT method inlining on inc method. When inlining is enabled I get surprisingly good examples 2s vs 4ns - what I would like to make sure or at least validate is that no loop optimisation took palace in the mean time. I took look at machine code which seems ok

0x000000010b22a4d6: mov 0x8(%rbp),%r10d  ; implicit exception: dispatches to 0x000000010b22a529
0x000000010b22a4da: cmp $0xf8033d43,%r10d  ;   {metadata('IncWhile$')}
0x000000010b22a4e1: jne L0001  ;*iload_3
                               ; - IncWhile$::main@4 (line 7)
0x000000010b22a4e3: cmp $0x3b9aca00,%ebx
0x000000010b22a4e9: jge L0000  ;*if_icmpge
                               ; - IncWhile$::main@7 (line 7)
0x000000010b22a4eb: sub %ebx,%r14d
0x000000010b22a4ee: add $0x3b9aca00,%r14d  ;*iadd
                                           ; - IncWhile$::inc@2 (line 16)
                                           ; - IncWhile$::main@12 (line 9)
0x000000010b22a4f5: mov $0x3b9aca00,%ebx  ;*if_icmpge
                                          ; - IncWhile$::main@7 (line 7)
             L0000: mov $0xffffff65,%esi

I also checked flight recorder and didn't find anything suspicious but as I am not regular user I would like to double check with someone more experienced. Code can be found on github


Solution

  • Of course, the loop has been optimized. No regular CPU can execute 1 billion operations in just a few nanoseconds.

    There are many loop optimizations in HotSpot - do you want to disable all of them? E.g.

    -XX:LoopUnrollLimit=0
    -XX:+UseCountedLoopSafepoints
    -XX:-UseLoopPredicate
    -XX:-PartialPeelLoop
    -XX:-LoopUnswitching
    -XX:-LoopLimitCheck
    

    etc. To disable most of loop optimizations, use

    -XX:LoopOptsCount=0