Java / Android - 为什么运行此代码会得到不同的运行时?

时间:2022-04-26 07:13:03

I wrote this code and I was surprised to see different runtime for everytime I run this code. Also I tried this on Android and I have the same problem And there are no other methods or class.

我编写了这段代码,每次运行此代码时,我都会惊讶地看到不同的运行时。我也在Android上尝试过这个问题,但我遇到了同样的问题。没有其他方法或类。

public class Sample1 {

    public static void main(String[] args) {

        long i = System.nanoTime();
        for (int k = 1; k <= 1000000; k++) {
            //
        }
        System.out.print(System.nanoTime() - i);
    }
}

1 个解决方案

#1


1  

Some machines will run the code faster than others. And it may run at different speeds on any given machine due to it sharing the CPU with other processes.

有些机器会比其他机器更快地运行代码。并且它可以在任何给定的机器上以不同的速度运行,因为它与其他进程共享CPU。

Also, some Java compilers will optimise out the for loop entirely as it's a no-op.

此外,一些Java编译器将完全优化for循环,因为它是一个无操作。

#1


1  

Some machines will run the code faster than others. And it may run at different speeds on any given machine due to it sharing the CPU with other processes.

有些机器会比其他机器更快地运行代码。并且它可以在任何给定的机器上以不同的速度运行,因为它与其他进程共享CPU。

Also, some Java compilers will optimise out the for loop entirely as it's a no-op.

此外,一些Java编译器将完全优化for循环,因为它是一个无操作。