Thread.sleep 有多准确? [英] How accurate is Thread.sleep?

查看:72
本文介绍了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.currentTimeMillisThread.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 实时系统规范.我自己没有使用过,所以我不能提供更多的细节.

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天全站免登陆