加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么System.nanoTime()在迭代开始时不正确?

发布时间:2020-12-15 04:25:34 所属栏目:Java 来源:网络整理
导读:我注意到了System.nanoTime()的模式.每当我开始迭代时,nanoTime()在几圈内变得非常不正确,直到它最终稳定下来. 例如,如果我运行以下代码: public class TimeTest{ public static void main(String[] args) { long prev = System.nanoTime(); for(int i = 0;
我注意到了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!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读