0

考虑以下代码

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()函数比 . 慢 10 倍currentTimeMillis

如果它更慢,拥有更精确的功能是什么意思?

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

更新

看看不确定性。nanoTime() 速度慢 10 倍,不确定性好 10 倍。

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

4

0 回答 0