1

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?

Abel Callejo
  • 13,779
  • 10
  • 69
  • 84
  • 1
    As an aside: a nanosecond is 1 millionth of a second, so to get the output of nanoTime() to millisecond scale you should divide by 1000000 rather than 1000. – jilles de wit May 04 '16 at 11:17

4 Answers4

7

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
0
       long currentTimeMillis = System.currentTimeMillis();     
       long nanos = TimeUnit.MILLISECONDS.toNanos(currentTimeMillis);
       System.out.println(nanos);
       System.out.println(TimeUnit.NANOSECONDS.toMillis(nanos)*1000000); 
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
  • 1
    Wow! this is one useful piece of script for handling **milliseconds** and **nanoseconds**. However, it seems it's not that directly related to this question. – Abel Callejo Aug 29 '13 at 15:51
0

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

Maverick
  • 626
  • 6
  • 11
0

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

kenyee
  • 2,309
  • 1
  • 24
  • 32