Windows 8(1)比需要多睡1毫秒

Windows 8(.1) Sleep 1 more ms than needed

本文关键字:1毫秒 Windows      更新时间:2023-10-16

SleepWindows 8.1 x64上总是比需要的时间多1毫秒。例如,Sleep(1)持续大约2毫秒,Sleep(2) - 3等。timeBeginPeriod设置为1。在Windows 7上按预期工作(没有多余的毫秒)。这种行为是正常的/可以修复吗?

#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, "%ldn", buffer[i]);
    fclose(file);
    return EXIT_SUCCESS;
}

NtDelayExecution解决方案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);