Wednesday, September 4

Why to use System.nanoTime() instead of System.currentTimeMillis()?

Why to use System.nanoTime() instead of System.currentTimeMillis()?
System.currentTimeMillis() system dependent while System.nanoTime() is not .

What is the impact?

System.currentTimeMillis() evaluates milliseconds from January 1 , 1970 mid night (UTC) . there are certain times in the year when clock correction is made.

Let us consider a scenario


long start= System.currentTimeMillis();
// some more code
System.out.print("time taken"+ System.currentTimeMillis()-start );


Lets say long start= System.currentTimeMillis(); is executed at a moment and just after that clock is corrected

and System.out.print("time taken"+ System.currentTimeMillis()-start ); is evaluated after clock correction ,


 In this calculation correction made (Clock correction)is also considered and that will give wrong result .

So System.currentTimeMillis() should be avoided

nanoTime() has no starting time to be calculated from(reference point like 1970 in currentTimeMillies) neither it is system dependent So it has no impact of clock correction.

No comments:

Post a Comment