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

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

  •  26-06-2022
  •  | 
  •  

문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

       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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top