使nanoTime比currentTimeMillis慢10倍的原因是什么?

时间:2015-05-06 17:21:02

标签: java nanotime

考虑以下代码

package tests;

public class Test_computer_speed {

    public static void main(String[] args) {

        for(int i=0; i<10; ++i) {
            testMillis();
        }

        for(int i=0; i<10; ++i) {
            testNanos();
        }

    }

    public static void testMillis() {


        long startTime = System.currentTimeMillis(), endTime = startTime + 6000, iterations = 0, now;
        while (true) {
            now = System.currentTimeMillis();
            if (now > endTime)
                break;
            iterations++;
        }

        System.out.println("In 6 seconds, the loop performed " + iterations + " iterations.");

    }

    public static void testNanos() {


        long startTime = System.nanoTime(), endTime = startTime + 6000000000l, iterations = 0, now;
        while (true) {
            now = System.nanoTime();
            if (now > endTime)
                break;
            iterations++;
        }

        System.out.println("In 6 seconds, the loop performed " + iterations + " iterations.");

    }

}

输出如下:

>java tests.Test_computer_speed
In 6 seconds, the loop performed 1402955969 iterations.
In 6 seconds, the loop performed 1452564156 iterations.
In 6 seconds, the loop performed 1443087123 iterations.
In 6 seconds, the loop performed 1417403052 iterations.
In 6 seconds, the loop performed 1451880195 iterations.
In 6 seconds, the loop performed 1444997459 iterations.
In 6 seconds, the loop performed 1438911291 iterations.
In 6 seconds, the loop performed 1461714025 iterations.
In 6 seconds, the loop performed 1460849690 iterations.
In 6 seconds, the loop performed 1441407031 iterations.
In 6 seconds, the loop performed 512124051 iterations.
In 6 seconds, the loop performed 524528348 iterations.
In 6 seconds, the loop performed 525100685 iterations.
In 6 seconds, the loop performed 528140105 iterations.
In 6 seconds, the loop performed 526142121 iterations.
In 6 seconds, the loop performed 526086430 iterations.
In 6 seconds, the loop performed 530290126 iterations.
In 6 seconds, the loop performed 529469812 iterations.
In 6 seconds, the loop performed 528229751 iterations.
In 6 seconds, the loop performed 529689093 iterations.

这意味着nanoTime()功能比currentTimeMillis慢10倍。

如果速度较慢,具有更精确功能的意义是什么?

换句话说,Java是作弊的,可能通过等待一段时间来获得精确度。

更新

看看不确定性。 nanoTime()的速度慢了10倍,不确定性提高了10倍。

这意味着绝对的不确定性是相同的。

0 个答案:

没有答案