How accurate is Sleep() or sleep()

杀马特。学长 韩版系。学妹 提交于 2019-12-04 04:26:26

问题


I'm trying simulate a key down and key up action.

For example: 2638 millseconds.

SendMessage(hWnd, WM_KEYDOWN, keyCode, 0);
Sleep(2638);
SendMessage(hWnd, WM_KEYUP, keyCode, 0);

How would you know if it really worked?


回答1:


You wouldn't with this code, since accurately measuring the time that code takes to execute is a difficult task.

To get to the question posed by your question title (you should really ask one question at a time...) the accuracy of said functions is dictated by the operating system. On Linux, the system clock granularity is 10ms, so timed process suspension via nanosleep() is only guaranteed to be accurate to 10ms, and even then it's not guaranteed to sleep for exactly the time you specify. (See below.)

On Windows, the clock granularity can be changed to accommodate power management needs (e.g. decrease the granularity to conserve battery power). See MSDN's documentation on the Sleep function.

Note that with Sleep()/nanosleep(), the OS only guarantees that the process suspension will last for at least as long as you specify. The execution of other processes can always delay resumption of your process.

Therefore, the key-up event sent by your code above will be sent at least 2.638 seconds later than the key-down event, and not a millisecond sooner. But it would be possible for the event to be sent 2.7, 2.8, or even 3 seconds later. (Or much later if a realtime process grabbed hold of the CPU and didn't relinquish control for some time.)




回答2:


Sleep works in terms of the standard Windows thread scheduling. It is accurate up to about 20-50 milliseconds.

So that it's ok for user experience-dependent things. However it's absolutely inappropriate for real-time things.

Beside of this, there're much better ways to simulate keyboard/mouse events. Please see SendInput.




回答3:


The sleep() function will return before the desired delay when the requested delay is shorter than the time left until the next interrupt occurs. But this only points out that you want to sleep for a shorter period of time than currently is supported by your system. It is advisable to setup the multimedia timer resource to a higher interrupt frequency to obtain better matching of the observed sleep delay with respect to the desired delay.

The the comments in the following threads:

How to get an accurate 1ms Timer Tick under WinXP

Sleep Less Than One Millisecond




回答4:


The command Sleep() will ensure that thread is suspended at least the amount of time which is given as argument. Operating system does not guarantee it. For detailed discussion you can refer the below post how is sleep implemented at OS level?



来源:https://stackoverflow.com/questions/4128766/how-accurate-is-sleep-or-sleep

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!