所以我写了一个相当愚蠢的程序,只是为了与nanoTime合作。我希望能够检查一小段代码的执行时间,所以我觉得nanoTime是最好的。我想确定这段短代码的平均执行时间,所以我把它放在for循环中。但是,当在for循环内时,平均值下降到约6,000纳秒。我知道这对小代码没什么大不同,但我很好奇为什么对于相同的代码会有什么不同呢? 这是产生不同时间的两个块: 这个平均约为8064纳秒:
long start, end, totalTime;
double milliseconds, seconds, minutes, hours, days, years;
totalTime = 0;
start = System.nanoTime();
milliseconds = System.currentTimeMillis();
seconds = milliseconds/1000;
minutes = seconds/60;
hours = minutes/60;
days = hours/24;
years = days/365;
end = System.nanoTime();
totalTime = end-start;
这个平均约为2200纳秒:
long start, end, totalTime;
double milliseconds, seconds, minutes, hours, days, years;
totalTime = 0;
for(int i = 1; i < 11; i++){
start = System.nanoTime();
milliseconds = System.currentTimeMillis();
seconds = milliseconds/1000;
minutes = seconds/60;
hours = minutes/60;
days = hours/24;
years = days/365;
end = System.nanoTime();
totalTime += end-start;
System.out.println(end-start); //this was added to manually calc. the average to
//make sure the code was executing properly. does not effect execution time.
}
然后找到你的总时间* .1
的平均值答案 0 :(得分:3)
这正是任何 Java程序所期望的。 Java运行时,特别是JIT编译器,将在程序的生命周期内运行得越多,代码就越大。您应该期望代码在多次运行后加速。