java - Why JVM does't execute the code? -
i'm testing branch prediction, code this:
//first loop int sortedsum = 0; long sortedstarttime = system.nanotime(); (int = 0; < sortedarray.length; i++) { if (sortedarray[i] < 0) { sortedsum += sortedarray[i]; } } long sortedtime = system.nanotime() - sortedstarttime; //second loop int randomsum = 0; long randomstarttime = system.nanotime(); (int = 0; < randomarray.length; i++) { if (randomarray[i] < 0) { randomsum += randomarray[i]; } } long randomtime = system.nanotime() - randomstarttime; system.out.println("random time: " + randomtime); system.out.println("sorted time: " + sortedtime);
it's simple print time each loop.
note sortedsum
, randomsum
assigned in loop never accessed.
we don't talk branch prediction here, output result. output is:
random time: 32 sorted time: 1595942
then, put second loop before first(first randomarray loop, second sortedarray). output is:
random time: 1541919 sorted time: 40
it seems jvm doesn't execute second loop. decompile class file, decompiler doesn't erase anything.
why? , why jvm execute first loop?
p.s. environment is:
ubuntu 12.04 lts java version "1.7.0_11" java(tm) se runtime environment (build 1.7.0_11-b21) java hotspot(tm) 64-bit server vm (build 23.6-b04, mixed mode)
when runtime code enough triggers whole method optimised (in background)
this means if have loop iterates on 10k times , doesn't anything, timing how long takes detect loop doesn't thing , replace it.
in case of second loop, method has been optimise away, in either case.
i suggest have outer loop runs test 3 times , should see mean.
the reason can drop loop is;
- and don't use value calculated,
calculatesum
can dropped - then array access isn't needed
- then loop isn't need.
Comments
Post a Comment