2

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.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
karth
  • 635
  • 3
  • 13
  • 25
  • 4
    how sure are you that both programs did run at the same instant? – Abhishek Nov 26 '16 at 06:34
  • 2
    This question is on topic, well formulated and includes code. I don't understand why it gets downvotes. – Modus Tollens Nov 26 '16 at 06:48
  • I should've probably formed the question better. I wanted to know why is the nanoTime inaccurate on java 8 compared to java 7. I updated the question to include outputs from gdate. – karth Nov 26 '16 at 07:06

1 Answers1

7

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.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • can you please tell me what does origin mean in this context? – Abhishek Nov 26 '16 at 08:47
  • @Abhishek A value computed at by the JRE and guaranteed to perform as stated in the documentation, the truth is most operating systems only offer precision to +/- 15ms. The JVM also only guarantees that `nanoTime` is *at least* as accurate [`currentTimeMillis()`](https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#currentTimeMillis--). – Elliott Frisch Nov 26 '16 at 08:56