当我阅读 Java 中的 System.nanoTime() API 时。我找到了这一行:
one should use t1 - t0 < 0, not t1 < t0, because of the possibility of numerical overflow.
http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#nanoTime()
To compare two nanoTime values
long t0 = System.nanoTime(); ... long t1 = System.nanoTime();
one should use t1 - t0 < 0, not t1 < t0, because of the possibility of numerical overflow.
我想知道为什么t1 - t0 < 0
是防止溢出的首选方法。
因为我从其他一些帖子中读到 A < B
比 A - B < 0
更可取.
Java Integer compareTo() - why use comparison vs. subtraction?
这两件事产生了矛盾。
最佳答案
纳米时间不是“真实”时间,它只是一个计数器,当发生某些未指定的事件(可能是计算机已启动)时,它会从某个未指定的数字开始递增。
它会溢出,并在某个时刻变成负数。如果你的t0
就在它溢出之前(即非常大的正值),而你的 t1
就在(非常大的负数)之后,然后是t1 < t0
(即你的条件是错误的,因为 t1
发生在 t0
之后)......
但是,如果你说 t1 - t0 < 0
,好吧,神奇的是,由于相同的溢出(下溢)原因(非常大的负值减去非常大的正值会下溢),结果将是 t1 在 t0
之后的纳秒数。 ..... 并且会是对的。
在这种情况下,两个错误确实是正确的!
关于java - 在 Java 中使用 System.nanoTime() 时,为什么我应该使用 t1 - t0 < 0,而不是 t1 < t0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18414059/