VC延時程式
阿新 • • 發佈:2018-12-17
1. 粗略延時, 精度為ms
#include <Mmsystem.h> #pragma comment(lib,"Winmm.lib") DWORD dwStart = timeGetTime(); while(true) { if( bStop ) //如果延時過程中被終止 break; DWORD dwEnd = timeGetTime(); if( (int)(dwEnd - dwStart) >= m_DelayTime ) //如果已超出延時時間 break; Sleep(1); }
2.較精確延時, 精度可為us [以下例子為ms]
#include <stdio.h> #include <windows.h> void VsSleepFre(int nDelayMS) //引數為ms { LARGE_INTEGER nFreq; LARGE_INTEGER nBeginTime; LARGE_INTEGER nEndTime; double time; QueryPerformanceFrequency(&nFreq); //獲取硬體頻率 QueryPerformanceCounter(&nBeginTime); //獲取當前計數 QueryPerformanceCounter(&nEndTime); //獲取當前計數 double TimeUs = 1000000.0 / ((double)nFreq.QuadPart); //us while(true) { QueryPerformanceCounter(&nEndTime); //獲取當前計數 time=(double)(nEndTime.QuadPart-nBeginTime.QuadPart) * TimeUs / (double)1000; //ms [可修改此式, 讓精度為us] if(time >= nDelayMS) { break; } Sleep(1); //精度為us時,此式需要註釋, 因Sleep引數為ms } }