Precision vs. accuracy of System.nanoTime()

后端 未结 4 1973
星月不相逢
星月不相逢 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:38

    If someone like me comes and reads this question again and again and again to still kind of understand it, here is a simpler (I hope) explanation.

    Precision is about how many digits you retain. Each of the:

    long start = System.nanoTime();
    long end   = System.nanoTime();
    

    is going to be a precise number (lots of digits).

    Since accuracy is measured only compared to something, an individual call to System.nanoTime makes no sense since it's value is quite arbitrary and does not depend on something that we can measure. The only way to distinguish it's accuracy is to two different calls of it, thus:

     long howMuch = end - start;
    

    is not going to have a nano-second accuracy. And in fact on my machine the difference is 0.2 - 0.3 micro-seconds.

提交回复
热议问题