使用System.nanoTime()

时间:2018-07-18 09:54:22

标签: java android

我在System.nanoTime()的android文档中找到了以下指南

  

由于可能出现数值溢出,因此应该使用t1-t0 <0,而不是t1

我真的很好奇比较将如何导致溢出。据我所知,当我们接近最高表示时,就会发生溢出,并且所得到的计算结果甚至会比可以实现的值更高。

1 个答案:

答案 0 :(得分:1)

我认为溢出不是在比较中发生,而是在时钟值中发生,每2 ^ 63纳秒周期发生一次,并且这种情况随时可能发生,因为它的来源是任意固定的(对于给定的虚拟机)

// say the clock value happens to be Long.MAX_VALUE - 10
long ts1 = 9223372036854775797L;

// 100 ns later it has overflowed (it is now negative)
long ts2 = ts1 + 100;

System.out.println("ts2 - ts1 > 0 : " + (ts2 - ts1 > 0));
System.out.println("ts2 > ts1 : " + (ts2 > ts1));

结果是:

ts2 - ts1 > 0 : true
ts2 > ts1 : false  <-- not correct