Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does System.nanoTime() take 4400 nano seconds

Tags:

java

I was testing some algorithms which I surrounded with a nanoseconds timer when I randomly forgot to remove the timer I found out that this code:

    a = System.nanoTime();
    System.out.println(System.nanoTime() - a);

always prints 4400 nano seconds on my system. That would be 4.4 microseconds whereas this code:

    a = System.currentTimeMillis();
    for (int i = 0; i < 1000; i++)
        System.nanoTime();
    System.out.println(System.currentTimeMillis() - a);

Prints 0

like image 223
Walter Lars Lee Avatar asked Oct 07 '22 23:10

Walter Lars Lee


1 Answers

4400 nanoseconds is 4.4 microseconds, or 0.0044 milliseconds. The second example will always print zero because the elapsed time is much less than one millisecond. Then there are the differences between the two timers used: currentTimeMillis can get adjusted for clock skew while nanoTime cannot, but I doubt that's in play here.

like image 132
Jim Garrison Avatar answered Oct 13 '22 00:10

Jim Garrison