所以我编写了一个相当愚蠢的程序,只是为了稍微使用 nanoTime。我希望能够检查一小段代码的执行时间,所以我认为 nanoTime 是最好的。我想确定这段短代码的平均执行时间,所以我将它放在一个 for 循环中。但是,在 for 循环内部时,平均值下降到大约 6,000 纳秒。我知道这在小代码上并没有太大的区别,但我很好奇为什么相同的代码会有什么不同? 这是产生不同时间的两个 block : 这个平均约为 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.
}
然后求出平均时间 totalTime*.1
最佳答案
这正是您对任何 Java 程序的期望。 Java 运行时,特别是 JIT 编译器,将在程序的整个生命周期中运行得越多,优化代码的力度就越大。您应该期望代码在多次运行后会加速。
关于java - 为什么相同的代码在 for 循环中会更短?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36585010/