我在以下代码中体验了(对我来说)奇怪的运行时行为:
public class Main{
private final static long ROUNDS = 1000000;
private final static double INITIAL_NUMBER = 0.45781929d;
private final static double DIFFERENCE = 0.1250120303d;
public static void main(String[] args){
doSomething();
doSomething();
doSomething();
}
private static void doSomething(){
long begin, end;
double numberToConvert, difference;
numberToConvert = INITIAL_NUMBER;
difference = DIFFERENCE;
begin = System.currentTimeMillis();
for(long i=0; i<ROUNDS; i++){
String s = "" + numberToConvert;
if(i % 2 == 0){
numberToConvert += difference;
}
else{
numberToConvert -= difference;
}
}
end = System.currentTimeMillis();
System.out.println("String appending conversion took " + (end - begin) + "ms.");
}
}
我希望程序每次打印出类似的运行时。但是,我得到的输出总是这样:
String appending conversion took 473ms.
String appending conversion took 362ms.
String appending conversion took 341ms.
第一次通话比之后的通话慢约30%。大多数情况下,第二次通话也比第三次通话稍慢。
java / javac版本:
javac 1.7.0_09 java version "1.7.0_09" OpenJDK Runtime Environment (IcedTea7 2.3.3) (7u9-2.3.3-0ubuntu1~12.04.1) OpenJDK 64-Bit Server VM (build 23.2-b09, mixed mode)
所以,我的问题:为什么会发生这种情况?
答案 0 :(得分:6)
即时(JIT)编译器正在动态分析您的代码并优化执行。执行代码的次数越多,优化效果就越好。
例如,请参阅此问题以获取更多信息:(How) does the Java JIT compiler optimize my code?
答案 1 :(得分:0)
您运行的其他应用程序可能会影响您在计算机上分配给JVM的内存量。尝试在运行java命令时为JVM设置相同的最小和最大内存:
java -Xms512M -Xmx512M ...
尝试运行时,我得到了相当一致的间隔:
String appending conversion took 1153ms.
String appending conversion took 1095ms.
String appending conversion took 1081ms.