我正在使用Amazon上的其中一本电子书自学Java。我正在上一个类,讲授计算机的“基准”。它通过循环一分钟并计算结果来做到这一点。

在完成之前,它基本上不会在一分钟内显示任何内容。所以我做了一个小小的修改,每隔几秒钟就会显示一个点作为进度条。通常这是一件微不足道的事情,但是有些事情是不对的,我也不知道是什么。

发生什么情况是miniIndex将达到我指定的阈值,并输出miniIndex的值和一个句点。然后应将miniIndex设置为零,以便计数器可以重新启动。但是它不会重置,并且永远不会再递增。这是非常奇怪的行为。

这是完整的代码:

class Benchmark {
    public static void main(String[] arguments) {

        long startTime = System.currentTimeMillis();
        long endTime = startTime + 60000;
        long index = 0;

        // My inner index
        int miniIndex = 0;
        //
        while (true) {
            double x = Math.sqrt(index);
            long now = System.currentTimeMillis();
            if (now > endTime){
                break;
            }
            index++;
            // my modification
            miniIndex++;
            if (miniIndex >= 5000) {
                System.out.print(miniIndex + ".");
                miniIndex = 0;
            }
            // end of my modification
        }
        System.out.println(index + " loops in one minute.");
    }
}

最佳答案

我认为您误解了miniIndex++操作正在执行的操作,因为它不是在计算毫秒,而是在计算彼此不相等的循环迭代次数。我已经修改了您的代码,根据您想发生的情况,每5秒执行一次if语句:

public static void main(String[] arguments) {

    long startTime = System.currentTimeMillis();
    long miniTime = startTime; //Declare miniTime equal to startTime
    long endTime = startTime + 60000;
    long index = 0;

    while (true) {
        double x = Math.sqrt(index);
        long now = System.currentTimeMillis();
        if (now > endTime){
            break;
        }
        index++;

        // my modification
        //Current time minus last time the if executed and check if 5 seconds passed
        if ((now - miniTime) >= 5000) {
            miniTime = System.currentTimeMillis();
            System.out.println("5 seconds have passed.");

            //if you want to print the actual time elapsed every 5 seconds use this print
            //System.out.println((now - startTime)/1000 + " seconds have passed.");
        }
        // end of my modification
    }
    System.out.println(index + " loops in one minute.");
}

请注意,现在我如何比较now的当前时间,并减去miniTime来检查其是否大于或等于5000毫秒。要使用时间,您必须以某种方式将其与时间相关联,在这种情况下为System.currentTimeMillis()和结果。数字本身(例如对循环进行计数)将永远不会保持时间一致。

循环可能执行数百万次,但只需要3秒钟。

示例输出:
5 seconds have passed.
5 seconds have passed.
5 seconds have passed.
5 seconds have passed.
5 seconds have passed.
5 seconds have passed.
5 seconds have passed.
5 seconds have passed.
5 seconds have passed.
5 seconds have passed.
5 seconds have passed.
16319642816 loops in one minute.

注意: 5 seconds have passed.可打印11次,因为在60秒标记处循环中断,因此不会打印最终通过。 (在最初的55秒中,11 * 5为55)。

09-27 23:06