Thread.sleep的准确度如何? [英] How accurate is Thread.sleep?

查看:179
本文介绍了Thread.sleep的准确度如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究计算机硬件,我们了解到使用硬件计时器可获得比软件延迟更准确的结果。我已经在汇编中写了一个软件延迟1毫秒,我可以开始一个使用这个延迟重复每个毫秒的过程,并且计数器每100毫秒做一次其他的事情,这种技术不如使用我的硬件计时器那么精确内置了我现在要使用的硬件。

I'm studying computer hardware where we learn that using a hardware timer gets more accurate results than a software delay. I've written a software delay in assembly for 1 millisecond and I can start a process that repeats every millisecod using this delay and with a counter do something else every 100th millisecond, and this technique would be less accurate than using a hardware timer that I got builtin with my hardware that I'm going to use now.

所以我想知道用Java构建的时序有多精确?我们有 System.currentTimeMillis Thread.sleep ,这些可能没有使用硬件计时器,所以这些内置Java有多准确方法与硬件计时器相比?

So I wonder how accurate is the timing that is builtin with Java? We have System.currentTimeMillis and Thread.sleep and these might not use hardware timers, so how accurate are these builtin Java methods compared to a hardware timer?

推荐答案

Thread.sleep()是不准确的。不准确程度取决于底层操作系统及其计时器和调度程序。我经历过并行进行的垃圾收集会导致睡眠过度。

Thread.sleep() is inaccurate. How inaccurate depends on the underlying operating system and its timers and schedulers. I've experienced that garbage collection going on in parallel can lead to excessive sleep.

在进行实时模拟时,您必须纠正主循环,以确定 sleep 的不准确性。这可以通过计算唤醒的预期时间并将其与唤醒的实际时间进行比较并校正下一循环中的差异来完成。

When doing "real time" simulations you have to correct your main loop for the inaccuracies of sleep. This can be done by calculating the expected time of wake-up and comparing that to the actual time of wake-up and correcting for the difference in the next loop.

如果您需要更好的表现,请查看Java Real - 时间系统规范。我自己没有用过,所以我无法提供进一步的细节。

If you need better performance, have a look at the Java Real-Time System specification. I haven't used it myself so I can't provide further details.

这篇关于Thread.sleep的准确度如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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