Precision vs. accuracy of System.nanoTime()

后端 未结 4 1972
星月不相逢
星月不相逢 2020-11-30 09:35

The documentation for System.nanoTime() says the following (emphasis mine).

This method can only be used to measure elapsed time and is not related to

4条回答
  •  北海茫月
    2020-11-30 10:32

    One quite interesting feature of the difference between System.currentTimeMillis() & System.nanoTime() is that System.nanoTime() does NOT change with the wall clock. I run code on a Windows virtual machine that has heavy time drift. System.currentTimeMillis() can jump back or forward by 1-2 seconds each time as NTP corrects that drift, making accurate time stamps meaningless. (Windows 2003, 2008 VPS editions)

    System.nanoTime() is not, however, affected by changing wall clock time so you can take a time retrieved over NTP and apply a correction based on System.nanoTime() since NTP was checked last and you have a far more accurate time than System.currentTimeMillis() in adverse wall clock conditions

    This is of course counter-intuitive, but useful to know

提交回复
热议问题