问题
I am making a code where I want definite precision in my timing. I use a robot to make some actions, then I use Thread.sleep(some_time)
for some_time
to be elapsed between the actions. But I don't get best results because as I search it, sleep
is not accurate. What would be the best way to accomplish this? I mean simulate Thread.sleep
with other methods.
回答1:
Timing in modern OSes is never precise, unless you use a language/framework that was explicitly designed for this. You can however work with a reasonable uncertainty in most operation systems. But "reasonable" depends on the problem you are trying to solve.
In Java Thread.sleep is a very basic implementation that is way too overused in my opinion. Java offers these basic threading tools not because they are the best solution, but because they are basic tools. Java as well offers many other, more sophisticated tools, that might suit your needs much better.
In example if you want "precise" timing, you can instead use a ScheduledExecutorService, which uses the OS scheduling service to offer a precision of at least milliseconds, and often even nanoseconds. Although it is not exact to the nanosecond (despite the offer), it will usually be much more accurate than Thread.sleep. But both will not be accurate on a heavily overloaded system. If this is sufficient for your problem, then you should go with this. Otherwise you need a different language/execution environment.
回答2:
In fact, Java relies on OS facilities to implement its timers1. The real reason that you don't get better than 1 millisecond accuracy on timers is that this is the limit of what a typical (non-realtime) OS provides. And even if the time resolution was finer, the OS still could not guarantee to "wake up" the user process at precisely the time that the application asked for.
If you need real (i.e. hard) realtime behaviour, including high precision timers and clocks, you need a realtime OS, and you need to run a Realtime Java on it.
1 - These are the same OS facilities that the C and C++ libraries use. So simply switching to C or C++ won't help much.
来源:https://stackoverflow.com/questions/23169557/thread-sleep-and-precise-timing