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;
}
答案 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);