Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 762
user2712734 Avatar asked Aug 24 '13 01:08

user2712734


People also ask

What does system nanoTime do in Java?

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.

Is system nanoTime () reliable?

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.

Is system nanoTime unique?

No, there is no guarantee that every call to System. nanoTime() will return a unique value.

Can system nanoTime be negative?

nanoTime() , the value, when the input data-set is large enough, turns negative.


1 Answers

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!

like image 68
rolfl Avatar answered Sep 27 '22 20:09

rolfl