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

时间:2014-05-04 13:03:55

标签: c++ winapi windows-8 windows-8.1

Sleep x64上的

Windows 8.1总是比所需的持续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, "%ld\n", buffer[i]);

    fclose(file);

    return EXIT_SUCCESS;
}

1 个答案:

答案 0 :(得分:0)

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);