System.nanoTime() returns java 7 和 java 8 之间的不同值

System.nanoTime() returns different values between java 7 and java 8

System.nanoTime() returns 编译相同代码时的不同值和 运行 针对 java 7 和 java 8.

这段代码:

public class nanoTime
{
    public static void main(String... args)
    {
      System.out.println("Found JVM: "
          + " " + System.getProperty("java.vm.vendor")
          + " " + System.getProperty("java.version")
          + " " + System.getProperty("java.vm.name")
          );
      System.out.println("time is "+ System.nanoTime());
    }
}

在 java 7

上打印
~ gdate +%s%N && javac7-oraclejdk nanoTime.java && java7-oraclejdk nanoTime
1480143769271605000
Found JVM:  Oracle Corporation 1.7.0_80 Java HotSpot(TM) 64-Bit Server VM
time is 1480143769807547000

和这个 java 8

~ gdate +%s%N && javac nanoTime.java && java nanoTime
1480143724152650000
Found JVM:  Oracle Corporation 1.8.0_92 Java HotSpot(TM) 64-Bit Server VM
time is 527819867675375

为什么以及如何发生这种情况?

运行时间环境是mac Sierra。

System.nanoTime() javadoc 说,

The same origin is used by all invocations of this method in an instance of a Java virtual machine; other virtual machine instances are likely to use a different origin.

The values returned by this method become meaningful only when the difference between two such values, obtained within the same instance of a Java virtual machine, is computed.

您正在比较不同 JVM 实例(以及不同来源和版本)的结果。那是没有意义的。只要保留 API 中指定的行为,在 Java 版本之间更改实现是完全合法的。