2

I make a benchmark like this :

for (int i = 0; i < 1000 * 1000; ++i) {
    long var = System.nanoTime();
}

it takes 41 ms in my computer with jdk6.0

the follow code only costs 1 ms!!!

for (int i = 0; i < 1000 * 1000; ++i) {
    System.nanoTime();
}

I think may be that time is costed by long var , so I make a test like this :

 for (int i = 0; i < 1000 * 1000; ++i) {
    long var = i;
}

it only costs 1 ms!!!

So,Why the first code block is so slow? I'm a Chinese. Sorry for my poor English!

2 Answers2

8

It really depends on how you run your benchmark. You most likely get <1ms runs because the JVM is not really running your code: it has determined that the code is not used and skips it:

for (int i = 0; i < 1000 * 1000; ++i) {
    long var = i;
}

is equivalent to

//for (int i = 0; i < 1000 * 1000; ++i) {
//    long var = i;
//}

and the JVM is probably running the second version.

You should read how to write a micro benchmark in Java or use a benchmarking library such as caliper.

Community
  • 1
  • 1
assylias
  • 321,522
  • 82
  • 660
  • 783
1

It takes time for the JIT to detect your code doesn't do anything useful. The more complicated the code, the longer it takes (or it might not detect it at all)

In the second and third cases, it can replace the code with nothing (I suspect you can make it 100x longer and it won't run any longer)


Another possibility is you are running all three tests in the same method. When the first loop iterates more than 10,000 times, the whole method is compiled in the background such that when the second and third loops run they have been removed.

A simple way to test this is to change the order of the loops or better to place each loop in its own method to stop this.

assylias
  • 321,522
  • 82
  • 660
  • 783
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130