Question

Sleep on Windows 8.1 x64 always lasts 1 more milliseconds than needed. For instance Sleep(1) lasts approximately 2 milliseconds, Sleep(2) - 3 etc. timeBeginPeriod is set to 1. On Windows 7 works fine as expected (without excess millisecond). Is this behaviour is normal / possible to fix?

#include <Windows.h>
#include <stdio.h>

#pragma comment(lib, "winmm.lib")

LARGE_INTEGER Frequency;

long long int GetCurrent()
{
    LARGE_INTEGER counter;

    QueryPerformanceCounter(&counter);

    return (1000000 * counter.QuadPart / Frequency.QuadPart);
}

int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    timeBeginPeriod(1);

    QueryPerformanceFrequency(&Frequency);

    const unsigned int count = 1000;

    long long int buffer[count];

    long long int lastTime = GetCurrent(), currentTime;

    for (unsigned int i = 0; i < count; i++)
    {
        currentTime = GetCurrent();

        buffer[i] = currentTime - lastTime;

        lastTime = currentTime;

        Sleep(1);
    }

    timeEndPeriod(1);

    FILE *file = fopen("log.txt", "w");

    for (unsigned int i = 0; i < count; i++)
        fprintf(file, "%ld\n", buffer[i]);

    fclose(file);

    return EXIT_SUCCESS;
}
Était-ce utile?

La solution

NtDelayExecution workaround thanks to Mehrdad.

static NTSTATUS (__stdcall *NtDelayExecution)(BOOL Alertable, PLARGE_INTEGER DelayInterval) = (NTSTATUS (__stdcall*)(BOOL, PLARGE_INTEGER)) GetProcAddress(GetModuleHandle(L"ntdll.dll"), "NtDelayExecution");

LARGE_INTEGER delay;

unsigned int milliseconds = 1;

delay.QuadPart = (milliseconds > 1) ? -10000LL * (milliseconds - 1) : -1LL;

NtDelayExecution(false, &delay);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top