The POSIX nanosleep() function is available in Linux, macOS, BSD, Unix, etc. MinGW / MSYS2 implements nanosleep for certain platforms -- x86_64, but not ARM currently. Cygwin implements nanosleep() for x86_64 and ARM. MSVC Visual Studio currently does not implement nanosleep().
nanosleep() provides relatively small precision sleep intervals for a thread. This is useful for games and hardware interfaces among other tasks. Affiliated POSIX functions include clock_gettime() and clock_getres().
Our C implementation of nanosleep(), clock_gettime(), and clock_getres() for Windows (MSVC, Intel oneAPI, MinGW, etc.) uses Waitable Timer Objects and similar elements of the Win32 API.
#if defined(WIN_NANOSLEEP)
is used instead of simply _MSC_VER
because as noted above, certain MinGW platforms currently lack nanosleep().
Perhaps over time, these platforms will gain nanosleep() support, so it's a best practice to check dynamically.
The C11 standard
timespec
is used by the win32_time.h
function interface.
Currently, the CLOCK_MONOTONIC
parameter is ignored by our implementation.
cmake -Bbuild
cmake --build build
Specify the sleep time in milliseconds. For example, to sleep for 0.5 second:
build/main 500
The execution time is dependent on system overhead and system load. Accuracy on Windows is lower than other OS generally. Using in a virtual machine also affects accuracy.
Execution time is estimated on Windows PowerShell like:
Measure-Command { build/main.exe 500 }
On other shells like
time build/main 500
Separately, we provide a C++ example that is cross-platform, assuming C++11.