karth
karth

Reputation: 655

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

System.nanoTime() returns different values when the same code is compiled and run against java 7 and java 8.

This piece of code:

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());
    }
}

prints this on 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

and this on 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

Why and how does this happen?

The runtime environment is mac Sierra.

Upvotes: 2

Views: 978

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201447

The System.nanoTime() javadoc says,

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.

and

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.

You are comparing results across different JVM instances (and with different origins and versions). That is not meaningful. It is perfectly legal for the implementation to change between Java versions, as long as the behavior specified in the API is preserved.

Upvotes: 7

Related Questions