【vc】高精度時間函數的使用
阿新 • • 發佈:2019-01-12
amp color 定義 定時 表示 per 2個 target title
方法一:
函數定義如下:
int UsSleep(int us);//返回實際的微秒延時時間
代碼實現如下:
1 //參數一表示 需要等待的時間 微秒為單位 2 int UsSleep(int us) 3 { 4 //儲存計數的聯合 5 LARGE_INTEGER fre; 6 //獲取硬件支持的高精度計數器的頻率 7 if (QueryPerformanceFrequency(&fre)) 8 { 9 LARGE_INTEGER run,priv,curr,res; 10 run.QuadPart = fre.QuadPart * us / 1000000;//轉換為微妙級 11 //獲取高精度計數器數值 12 QueryPerformanceCounter(&priv); 13 do 14 { 15 QueryPerformanceCounter(&curr); 16 } while (curr.QuadPart - priv.QuadPart < run.QuadPart); 17 curr.QuadPart -= priv.QuadPart; 18 int nres = (curr.QuadPart * 1000000/ fre.QuadPart);//實際使用微秒時間 19 return nres; 20 } 21 return -1;//返回錯誤值。 22 }
在實際的使用過程中方法時間誤差在1微秒。
方法二:
timeBeginPeriod(1); Sleep(1); DWORD dwTime = ::timeGetTime(); timeEndPeriod(1);
被包含在timeBeginPeriod和timeEndPeriod裏面的Sleep和timeGetTime的
時間精度就是1ms,出了period函數對,還是原來的時間精度。
這麽說你就應該懂了,當你需要時間精度為1ms時,就寫個period函數對。
這2個period函數一般是成對出現。
參考:
Windows微秒級定時方法
windows開發,如何使Sleep函數精確到1毫秒
【vc】高精度時間函數的使用