[issue45429] [Windows] time.sleep() should use CREATE_WAITABLE_TIMER_HIGH_RESOLUTION

Eryk Sun report at bugs.python.org
Mon Oct 11 19:26:20 EDT 2021


Eryk Sun <eryksun at gmail.com> added the comment:

It's up to the core devs whether or not Python should try to use a high-resolution timer, which is currently undocumented in the Windows API and implemented only in recent releases of Windows 10 and 11. But if this does get supported, the code should fall back on creating a normal timer if CREATE_WAITABLE_TIMER_HIGH_RESOLUTION makes the call fail. For example:

    #ifndef CREATE_WAITABLE_TIMER_HIGH_RESOLUTION
    #define CREATE_WAITABLE_TIMER_HIGH_RESOLUTION 0x00000002
    #endif

        LARGE_INTEGER relative_timeout;
        // No need to check for integer overflow, both types are signed
        assert(sizeof(relative_timeout) == sizeof(timeout_100ns));
        // SetWaitableTimerEx(): a negative due time is relative
        relative_timeout.QuadPart = -timeout_100ns;
        DWORD flags = CREATE_WAITABLE_TIMER_HIGH_RESOLUTION;

    create_timer:

        HANDLE timer = CreateWaitableTimerExW(NULL, NULL, flags, TIMER_ALL_ACCESS);
        if (timer == NULL)
        {
            if (flags && GetLastError() == ERROR_INVALID_PARAMETER) {
                // CREATE_WAITABLE_TIMER_HIGH_RESOLUTION is not supported.
                flags = 0;
                goto create_timer;
            }
            PyErr_SetFromWindowsErr(0);
            return -1;
        }

        if (!SetWaitableTimerEx(timer, &relative_timeout,
              0,          // no period; the timer is signaled once
              NULL, NULL, // no completion routine
              NULL,       // no wake context; do not resume from suspend
              0))         // no tolerable delay for timer coalescing
        {
            PyErr_SetFromWindowsErr(0);
            goto error;
        }

----------
nosy: +eryksun

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue45429>
_______________________________________


More information about the Python-bugs-list mailing list