java - 为什么两个不同的嵌套循环(具有相同的时间复杂度)执行时间不同?

标签 java for-loop time

在我的代码中,for循环具有相同的时间复杂度和相同的操作,但是第二个嵌套 for循环比第一个循环花费了几乎 40 倍的时间。为什么会发生这种情况?

我正在使用 javac 编译器并在 Windows 命令提示符中运行我的代码。

import java.util.concurrent.TimeUnit;

class Elapsedtime
{
    public static void main(String[] args) throws InterruptedException 
    {
        int i,j,t,a;
        long startTime = System.nanoTime();
        for(i=0;i<1000000000;i++)
        {
            for(j=0;j<1000000000;j++)
            {
                a=j;
            }
        }
        long endTime = System.nanoTime();
        long timeElapsed = endTime - startTime;
        System.out.println("Execution time in nanoseconds  : " + timeElapsed + " ns.");
        System.out.println("Execution time in milliseconds : " + timeElapsed / 1000000 + " ms.");

        startTime = System.nanoTime();
        for(t=0;t<1;t++)
        {
            for(i=0;i<1000000000;i++)
            {
                for(j=0;j<1000000000;j++)
                {
                    a=j;
                }
            }
        }

        endTime = System.nanoTime();
        timeElapsed = endTime - startTime;
        System.out.println("Execution time in nanoseconds  : " + timeElapsed + " ns.");
        System.out.println("Execution time in milliseconds : " + timeElapsed / 1000000 + " ms.");
    }
}

我得到以下输出。

Execution time in nanoseconds : 17963700 ns. Execution time in milliseconds : 17 ms. Execution time in nanoseconds : 549485500 ns. Execution time in milliseconds : 549 ms.

但我预计不会有太大差异。

最佳答案

在第一个嵌套循环期间,优化编译器可能会创建更好的代码,因为它确定将有很多迭代。第二个循环将已经运行优化后的代码。

您可以通过颠倒两个循环的顺序来测试这一点,但第一个循环可能会更慢。

关于java - 为什么两个不同的嵌套循环(具有相同的时间复杂度)执行时间不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57285378/

相关文章:

python - 在Python中比较unix时间戳

java - 从其他 Intellij 项目导入/使用代码

python - For 循环未迭代预期的时间量

java - 在外层集合中查找,从内层集合中添加

c++ - 奇怪的错误。在循环中使用 rand() 和数组

Python 的 time.sleep() 方法等待的时间不正确

php - 比较php中的两个时间戳

java - 在单个程序中制作多个帧

java - org.glassfish.jersey.server.ContainerException : java. io.IOException:流关闭

java - 关于 java 枚举的一个不好的做法