放出几个珍藏多年的延时函数(高低精度高低性能)

#include "stdafx.h"
#include "delay.h"



void DoEvents()
{
	MSG msg;
	while (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE)) {
		if (msg.message == WM_QUIT)
		{
			return;
		}
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
}

//@(1)@延时 优点:低cpu;缺点:程序被卡死。
void NormalDelay(DWORD dwMilliSecond)
{
	Sleep(dwMilliSecond);
}

//@(2)@ 高精度,狂占CPU,单位微秒
void LowPerformanceHighPrecisionDelay(LONGLONG llMicrosecond)
{

	LARGE_INTEGER CurrTicks, TicksCount;

	QueryPerformanceFrequency(&TicksCount);
	QueryPerformanceCounter(&CurrTicks);

	TicksCount.QuadPart = TicksCount.QuadPart * llMicrosecond / 1000000ll;
	TicksCount.QuadPart += CurrTicks.QuadPart;
	while (CurrTicks.QuadPart < TicksCount.QuadPart)
	{
		QueryPerformanceCounter(&CurrTicks);
	}
}



DWORD WINAPI DelayInThread(LPVOID lpParam)
{
	DWORD* pMillSecond = (DWORD*)lpParam;
	Sleep(*pMillSecond);
	return 0;
}


//@(3)@多线程实现的不卡死、低cpu,低精度
BOOL HighPerformanceLowPrecisionDelayDelay(DWORD dwMilliSecond)
{
	HANDLE hThread;
	DWORD  RethThread;
	hThread = ::CreateThread(nullptr, 0, DelayInThread, &dwMilliSecond, 0, &RethThread);
	if (hThread == NULL)
	{
		return FALSE;
	}

	for (;;)
	{
		DoEvents();

		if (WAIT_TIMEOUT == WaitForSingleObject(hThread, 1))
		{
		}
		else
		{
			break;
		}
	}
	CloseHandle(hThread);
	return TRUE;
}




//不卡死、低cpu,高精度延时,毫秒
BOOL HighPerformanceHighPrecisionDelay(UINT64 n64MilliSecond)
{
	HANDLE hTimer;
	LARGE_INTEGER liDueTime;

	liDueTime.QuadPart = -10 * n64MilliSecond * 1000LL;

	DoEvents();

	hTimer = CreateWaitableTimer(nullptr, FALSE, nullptr);
	if (NULL == hTimer)
	{
		return	FALSE;
	}

	if (!SetWaitableTimer(hTimer, &liDueTime, 0, NULL, NULL, 0))
	{
		//printf("SetWaitableTimer failed (%d)\n", GetLastError());
		return FALSE;
	}

	DWORD ret;
	while (ret = MsgWaitForMultipleObjects(1, &hTimer, FALSE, INFINITE, QS_ALLINPUT) != WAIT_OBJECT_0)
	{
		if (((WAIT_OBJECT_0 + 1) == ret) || (WAIT_TIMEOUT == ret))
		{
			DoEvents();
		}
		else
		{
			//WAIT_TIMEOUT,WAIT_FAILED
			break;
		}
	}

	CancelWaitableTimer(hTimer);

	CloseHandle(hTimer);

	DoEvents();

	return TRUE;

}

你可能感兴趣的:(WIN32,API)