为什么我应该使用t1 - t0 < 0,而不是t1 < t0,当在JAVA中使用System.nanoTime()时 [英] Why should I use t1 - t0 &lt; 0, not t1 &lt; t0, when using System.nanoTime() in JAVA

查看:421
本文介绍了为什么我应该使用t1 - t0 < 0,而不是t1 < t0,当在JAVA中使用System.nanoTime()时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在JAVA中阅读System.nanoTime()API时。我找到这行:

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


应该使用t1 - t0< 0,而不是t1 <

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


比较两个nanoTime值

To compare two nanoTime values

long t0 = System.nanoTime();
...
long t1 = System.nanoTime();

应该使用t1 - t0 < 0,而不是t1 <

one should use t1 - t0 < 0, not t1 < t0, because of the possibility of numerical overflow.

我想知道为什么 t1 - t0 < 0

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

因为我从一些其他线程读取 A< B A-B < 0

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

Java Integer compareTo() - 为什么要使用比较和减法?

这两个问题产生矛盾。

These two things make contradiction.

推荐答案

纳米时间不是一个真正的时间,它只是一个计数器从一些未指定的数字未指定的事件发生(也许计算机已启动)。

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).

它会溢出,并在某一时刻变为负值。如果你的 t0 刚好在它溢出之前(即非常大的正数),你的 t1 负数),则 t1 < t0 (即您的条件错误,因为 t1 发生在 t0 之后) 。

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).....

但是,如果你说 t1 - t0< 0 ,很好,神奇的是,对于相同的溢出(undeflow)原因(非常大负减去非常大的正将会下溢),结果将是纳秒数, code> 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.

在这种情况下,

这篇关于为什么我应该使用t1 - t0 < 0,而不是t1 < t0,当在JAVA中使用System.nanoTime()时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆