Fix nanosleep returning negative rem

Lavrentiev, Anton (NIH/NLM/NCBI) [C] lavr@ncbi.nlm.nih.gov
Wed Jul 21 17:57:30 GMT 2021


> I can get it easily get this on my desktop (AMD Ryzen Threadripper 3990X) but not at all on my laptop (Intel Core i7-8650U)

Not sure if that's really related but:

Have you checked what is your default Windows timer resolution?  Some applications change it from the default
100HZ to 1000HZ (by e.g. using timeBeginPeriod(1) -- MS Edge does this, and Chrome, I think, but not Firefox -- yet
the change is actually _global_ as documented).

The following code shows the timer resolution:

#include <windows.h>
#include <timeapi.h>
#include <stdio.h>
#include <synchapi.h>

int main()
{
    unsigned int prev = timeGetTime(), next;
    Sleep(1);
    next = timeGetTime();
    printf("Sleep(1) = %u\n", next - prev);
    return 0;
}

Output:

Sleep(1) = 10
means the default 100HZ

Sleep(1) = 1
means the increased resolution of 1ms

Anton Lavrentiev
Contractor NIH/NLM/NCBI

P.S. timeBeginPeriod():

This function affects a global Windows setting. Windows uses the lowest value (that is, highest
resolution) requested by any process. Setting a higher resolution can improve the accuracy of
time-out intervals in wait functions. However, it can also reduce overall system performance,
because the thread scheduler switches tasks more often. High resolutions can also prevent the
CPU power management system from entering power-saving modes.


More information about the Cygwin-patches mailing list