Java System.nanoTime() vs System.currentTimeMillis(). Why do they have different outputs?

StackOverflow https://stackoverflow.com/questions/18513767

  •  26-06-2022
  •  | 
  •  

Question

Given the following Java code:

class Tester
    {
    public static void main(String[] args)
        {
        System.out.println((System.nanoTime()/1000));
        System.out.println(System.currentTimeMillis());
        }
    }

It gave an output of

2626051678558
1377785791569

I was expecting a little difference between the two but I was wrong.
Do you have any idea guys why it behaved like that?

Was it helpful?

Solution

Read the method's javadoc

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary origin time (perhaps in the future, so values may be negative). 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.

nanoTime() is not showing you the time.

OTHER TIPS

       long currentTimeMillis = System.currentTimeMillis();     
       long nanos = TimeUnit.MILLISECONDS.toNanos(currentTimeMillis);
       System.out.println(nanos);
       System.out.println(TimeUnit.NANOSECONDS.toMillis(nanos)*1000000); 

nanoTime(), as the java doc says, is a precision timer. currentTimeMillis() is NOT A TIMER, it is the "wall clock". nanoTime() will always produce positive elapsed time, currentTimeMillis will not (e.g. if you change the date, hit a leap second, etc.)

If you're on Android, nanoTime is affected by deep sleep modes. Use SystemClock.elapsedRealtime() (which returns msec) instead

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top