user2712734 user2712734 - 3 months ago 14
Java Question

Why should I use t1 - t0 < 0, not t1 < t0, when using System.nanoTime() in JAVA

When I was reading System.nanoTime() API in JAVA. I found this line:


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.


I want to know why
t1 - t0 < 0
is preferable way to prevent overflow.

Because I read from some other thread that
A < B
is more preferable than
A - B < 0
.

Java Integer compareTo() - why use comparison vs. subtraction?

These two things make contradiction.

Answer

The Nano time is not a 'real' time, it is just a counter that increments starting from some unspecified number when some unspecified event occurs (maybe the computer is booted up).

It will overflow, and become negative at some point. If your t0 is just before it overflows (i.e. very large positive), and your t1 is just after (very large negative number), then t1 < t0 (i.e. your conditions are wrong because t1 happened after t0).....

But, if you say t1 - t0 < 0, well, the magic is that a for the same overflow (undeflow) reasons (very large negative subtract a very large positive will underflow), the result will be the number of nanoseconds that t1 was after t0..... and will be right.

In this case, two wrongs really do make a right!

Comments