3

我对 Java 中 System.nanoTime() 方法的文档中的以下语句很感兴趣:

long t0 = System.nanoTime();

...

long t1 = System.nanoTime();

应该使用t1 - t0 < 0,不要t1 < t0,因为数值溢出的可能性

来源:http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#nanoTime()

为什么它t1 < t0可能会“溢出”?这在 Javadocs 中,但我想它适用于任何语言。

4

2 回答 2

2

不是<可能溢出,而是t2可能溢出。

十六进制的例子,因为溢出在十六进制中很明显。

假设你打电话System.nanoTime(),结果是0x7FFFFFFF00000000。这非常接近 a 的最大值long。这是t1.

几秒钟后,您再次调用它,并得到0x8000000011111111. 这非常接近 a 的最小值long——这意味着它比你得到的第一个值要小得多!这是t2.

如果你检查t2 < t1,你会得到false,因为t2确实小于t1

如果计算差异t2 - t1,这也会溢出,但碰巧这总是会抵消第一次溢出(如果有的话)。结果是0x0000000111111111正确的时差。这大于 0,所以t2 - t1 > 0返回true

于 2014-07-15T09:23:55.433 回答
1

除了immibis所说的,这个来源解释了a < b 和ab < 0 with big long 的区别:

    long t1 = Long.MAX_VALUE;
    long t2 = Long.MIN_VALUE;
    //should have the same result with small longs, but is different when rotating from max value to min value of Long
    System.out.println(t1 - t2 < 0); //true
    System.out.println(t1 < t2); //false

    //should have the same result
    System.out.println(t1 - t2 > 0); // false
    System.out.println(t1 > t2); //true

    System.out.println(t2 - t1); // 1 => 1 nanosecond of difference

由于 nanoseond 中的时间可以超过“长”大小,因此当时间到达最大值时,它会再次开始到最小值。所以 MAX_VALUE 和 MIN_VALUE 之间有 1 纳秒的差异

于 2014-07-15T09:34:10.200 回答