System.nanoTime()
针对 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 版本之间更改实现是完全合法的。
关于java - System.nanoTime() 在 java 7 和 java 8 之间返回不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40815674/