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.
nanoTime() method returns the current value of the most precise available system timer, in nanoseconds. The value returned represents nanoseconds since some fixed but arbitrary time (in the future, so values may be negative) and provides nanosecond precision, but not necessarily nanosecond accuracy.
nanoTime is significantly usually more accurate than currentTimeMillis but it's a relatively expensive call as well. currentTimeMillis() runs in a few (5-6) cpu clocks, nanoTime depends on the underlying architecture and can be 100+ cpu clocks.
No, there is no guarantee that every call to System. nanoTime() will return a unique value.
nanoTime() , the value, when the input data-set is large enough, turns negative.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With