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

6.4k views Asked by At

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?

4

There are 4 answers

0
Sotirios Delimanolis On BEST ANSWER

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.

0
kenyee On

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

1
Prabhakaran Ramaswamy On
       long currentTimeMillis = System.currentTimeMillis();     
       long nanos = TimeUnit.MILLISECONDS.toNanos(currentTimeMillis);
       System.out.println(nanos);
       System.out.println(TimeUnit.NANOSECONDS.toMillis(nanos)*1000000); 
0
Maverick On

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.)