java – 为什么System.nanoTime()在迭代开始时不正确?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 为什么System.nanoTime()在迭代开始时不正确?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1512字,纯文字阅读大概需要3分钟。
内容图文
![java – 为什么System.nanoTime()在迭代开始时不正确?](/upload/InfoBanner/zyjiaocheng/745/942db10df7f84059ae0ca52c9bd81201.jpg)
我注意到了System.nanoTime()的模式.每当我开始迭代时,nanoTime()在几圈内变得非常不正确,直到它最终稳定下来.
例如,如果我运行以下代码:
public class TimeTest{
public static void main(String[] args) {
long prev = System.nanoTime();
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 1000000; j++);
long time = System.nanoTime();
System.out.println(time - prev);
prev = time;
}
}
}
我得到以下结果:
为了消除Sys??tem.out.println(String)弄乱结果的可能性,我还可以运行以下测试:
public class TimeTest{
public static void main(String[] args) {
long[] difs = new long[10];
long prev = System.nanoTime();
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 1000000; j++);
long time = System.nanoTime();
difs[i] = (time - prev);
prev = time;
}
for(long l : difs)
System.out.println(l);
}
}
这给出了以下结果:
可以通过假设迭代的开始(在这种情况下为for循环)在循环开始之前花费一些额外的时间来初始化来解释初始延迟.然而,由于第二圈据说也需要很长时间才能执行,我们可以相信它毕竟不是for-loop.
所以我的问题很简单,当使用System.nanoTime()和迭代时导致这种初始延迟的原因是什么?
注意:我也尝试过不同类型的迭代器,但问题仍然存在.
解决方法:
这看起来像JIT warm up time of the JVM
The Java HotSpot compiler kicks in when it sees a ‘hot spot’ in your
code. It is therefore quite common that your code will run faster over
time! So, you should adapt your testing methods.The HotSpot compiler compiles in the background, eating away CPU
cycles. So when the compiler is busy, your program is temporarily
slower. But after compiling some hot spots, your program will suddenly
run faster!
内容总结
以上是互联网集市为您收集整理的java – 为什么System.nanoTime()在迭代开始时不正确?全部内容,希望文章能够帮你解决java – 为什么System.nanoTime()在迭代开始时不正确?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。