在Windows 8.1 x64中,Sleep
总是比所需的多睡眠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;
}
Windows 7
(以及可能在其他早期系统上),使用设置了平均值的timeBeginPeriod
的Sleep
大约是请求的值。但在Windows 8.1
上,它总是会增加+1毫秒的超额时间。我认为这种行为相当奇怪。 - DemionNtDelayExecution
? - user541686