![]() |
High resolution replacement for Sleep - Printable Version +- PowerBASIC Users Meeting Point (http://pump.richheimer.de) +-- Forum: User to User Discussions (http://pump.richheimer.de/forumdisplay.php?fid=3) +--- Forum: Source Code Library (http://pump.richheimer.de/forumdisplay.php?fid=8) +--- Thread: High resolution replacement for Sleep (/showthread.php?tid=59) |
High resolution replacement for Sleep - David Roberts - 09-01-2025 SleepX() SleepX() is a high resolution replacement for Sleep. The principle used has an analogy with HiFi were a class B amplifier is used to get us within a neighbourhood of a desired voltage and then uses a class A amplifier to fine tune. The cost of this approach is much less than using only a class A amplifier, which are expensive. The class B amplifier analogy uses Sleep and the class A amplifier analogy uses the Performance Counter, which has a resolution of 100ns with Windows 10 and later. The following code has the SleepX() code and a usage example. This is a typical output. Code: Quarter of a millisecond: .2503 ms The first example looks at a delay of a quarter of a millisecond. I doubt that anyone will have a use for that. The second example looks at a delay of two seconds. The third example looks at a 'silly' delay of 1234ms, The following looks at delays from 1ms to 30ms in steps of 1ms. All the results have a sub micro accuracy inline with the Performance Counter on Windows 10 and later. SleepX() has two parts: The first part is used for delays <= to 3ms and only polls the Performance Counter. This is expensive but is a short-lived expense and should not impact on the system performance. The second part uses the construct 'Sleep ( n-3 )' to get us within a neighbourhood of the target delay, and then we poll the Performance Counter to fine tune. 'Sleep ( n-3 )' needs a resolution of 1ms and why we use SetHiRes. 'Sleep ( n-3 )' does not use any CPU load. The CPU load only kicks in when we enter the 'class A' mode, so is an absolute value and should not impact on the system performance. Why was 'n <= 3'. It is reasonable to expect a 1ms resolution to give a delay of between n ms and n+1 ms. In practice, we can exceed n+1 ms and about one third of delays do just that. It is very rare, but values approaching n+1.5 ms have been seen. To mitigate that issue, 'n <= 3' was chosen. That is it: A very simple idea to give a high resolution replacement for Sleep with a negligible CPU load. It is worth noting that Code: SetHiRes Code: #COMPILE EXE |