0)); System.out.p-6ren">
gpt4 book ai didi

java - 使用 System.nanoTime() 时比较如何导致数值溢出

转载 作者:行者123 更新时间:2023-11-29 23:46:00 25 4
gpt4 key购买 nike

我在System.nanoTime()的android文档中找到了以下指南

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

我真的很好奇比较会导致溢出。据我所知,当我们接近最高表示时会发生溢出,并且由此产生的计算结果甚至比可以实现的值更高。

最佳答案

我认为溢出不会发生在比较中,而是发生在时钟值中,每 2^63 纳秒周期一次,这可能随时发生,因为它的原点是任意固定的(对于给定的虚拟机)

// say the clock value happens to be Long.MAX_VALUE - 10
long ts1 = 9223372036854775797L;

// 100 ns later it has overflowed (it is now negative)
long ts2 = ts1 + 100;

System.out.println("ts2 - ts1 > 0 : " + (ts2 - ts1 > 0));
System.out.println("ts2 > ts1 : " + (ts2 > ts1));

结果是:

ts2 - ts1 > 0 : true
ts2 > ts1 : false <-- not correct

关于java - 使用 System.nanoTime() 时比较如何导致数值溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51398967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com