简体   繁体   English

Java中奇怪的代码计时行为

[英]Strange code timing behavior in Java

In the following code: 在以下代码中:

long startingTime = System.nanoTime();
int max = (int) Math.pow(2, 19);
for(int i = 0; i < max; ){
    i++;
}
long timePass = System.nanoTime() - startingTime;
System.out.println("Time pass " + timePass / 1000000F);

I am trying to calculate how much time it take to perform simple actions on my machine. 我正在尝试计算在我的机器上执行简单操作所需的时间。

All the calculations up to the power of 19 increase the time it takes to run this code, but when I went above 19(up to max int value 31) I was amazed to discover that it have no effect on the time it takes. 所有高达19的幂的计算都会增加运行此代码所需的时间,但当我超过19(达到max int值31)时,我惊讶地发现它对所需的时间没有影响。 It always shows 5 milliseconds on my machine!!! 它总是在我的机器上显示5毫秒!

How can this be? 怎么会这样?

You have just witnessed HotSpot optimizing your entire loop to oblivion. 您刚刚目睹了HotSpot将您的整个循环优化为遗忘。 It's smart . 这很聪明 You need to do some real action inside the loop. 你需要在循环中做一些真正的动作。 I recommend introducing an int accumulator var and doing some bitwise operations on it, and finally printing the result to ensure it's needed after the loop. 我建议引入一个int accumulator var并对其进行一些按位操作,最后打印结果以确保在循环后需要它。

On the HotSpot JVM, -XX:CompileThreshold=10000 by default. 在HotSpot JVM上,默认情况下-XX:CompileThreshold=10000 This means a loop which iterates 10K times can trigger the whole method to be optimised. 这意味着迭代10K次的循环可以触发整个方法的优化。 In your case you are timing how long it take to detect and compile (in the background) your method. 在您的情况下,您需要计算检测和编译(在后台)您的方法所需的时间。

use another System.nanoTime() in the loop. 在循环中使用另一个System.nanoTime()。 no one can optimize this. 没有人可以优化这一点。

for(int i = 0; i < max; ){
i++;
dummy+=System.nanoTime();
}

dont forget to do: 别忘了做:

System.out.println(dummy);

after the loop. 循环之后。 ensures non-optimization 确保非优化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM