我希望计算从Java中的特定时间开始经过的时间(以毫秒为单位)。
经典的使用方式System.currentTimeMillis();
作为开始时间,然后再次将其与前一个时间一起使用来获取经过的时间。我希望做类似的事情,但不依赖系统时间。
如果我依赖系统时间,程序的用户就可以操纵系统时钟来破解程序。
我尝试使用类似于以下的代码:
int elapsed = 0;
while (true) {
Thread.sleep(10);
elapsed += 10;
}
这可行,但在计算机滞后然后锁定一两秒的情况下,它不太可靠。
有人有什么想法吗?
你想利用System.nanoTime
。它与系统时钟无关。它只能用于跟踪相对时间,这似乎就是您想要做的。
为了防止这个答案只是另一个答案的链接,这里有一个简短的解释。
来自文档
公共静态长nanoTime()返回最大的当前值
精确的可用系统计时器,以纳秒为单位。
This method can only be used to measure elapsed time and is not
related to any other notion of system or wall-clock time. The value
returned represents nanoseconds since some fixed but arbitrary time
(perhaps in the future, so values may be negative). This method
provides nanosecond precision, but not necessarily nanosecond
accuracy. No guarantees are made about how frequently values change.
Differences in successive calls that span greater than approximately
292 years (263 nanoseconds) will not accurately compute elapsed time
due to numerical overflow.
计时器信息的另一个链接:https://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks https://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks
您可以使用 Java 的 Timer 类以某个特定精度(假设每 500 毫秒)生成一个“检查”回调。此回调不会用于确定 500ms 确实过去了。你会打电话System.nanoTime
在回调中并将其与您上次调用的时间进行比较System.nanoTime
。无论挂钟如何变化,这都会为您提供相当准确的过去时间量表示。
你可以在这里看看:System.currentTimeMillis 与 System.nanoTime https://stackoverflow.com/questions/351565/system-currenttimemillis-vs-system-nanotime
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)