一、前言
因为接手的一个项目要做到精确到1ms以内的定时触发功能,在测试过 Sleep(DWORD millsecond)函数的准确度之后,该函数不能满足要求。上网查询了相询了相关资料,现将测试过程总结一下,方便自己以后翻阅。
二、测试过程
1.开发平台:系统windows 7 + vs2013 + win32
2.相关代码
代码1如下所示:
1 #include "stdafx.h" 2 #include <iostream> 3 #include <vector> 4 #include "math.h" 5 #include "windows.h" 6 #include "stdio.h" 7 8 using namespace std; 9 10 //是否调用Sleep()函数的阈值 11 #define VALUE_NO_SLEEP 8 12 13 14 15 /// 16 //函数功能:精确延时函数 17 //函数参数:延时时间 18 //返回值:实际延时时间 19 double MyDelay(double millsecond) 20 { 21 LARGE_INTEGER litmp; 22 LONGLONG qt1, qt2; 23 double dft, dff, dfm; 24 25 //获得时钟频率 26 QueryPerformanceFrequency(&litmp);//获得时钟频率 27 dff = (double)litmp.QuadPart; 28 29 //获得初始值 30 QueryPerformanceCounter(&litmp); 31 qt1 = litmp.QuadPart; 32 33 double delayTime = 0; 34 if (millsecond > VALUE_NO_SLEEP) //10ms 的效果会比较好,效果好于5ms、6ms、8ms 35 { 36 Sleep(millsecond - VALUE_NO_SLEEP); 37 } 38 39 //程序延时 40 do 41 { 42 //除法运算用于耗时 43 double tmp = 1.0 / 3; 44 QueryPerformanceCounter(&litmp); 45 qt2 = litmp.QuadPart; 46 47 //获得精确时间值,转到毫秒单位上 48 dft = (double)(qt2 - qt1)/dff; 49 //dft = dfm / dff; 50 //printf("当前用时: %.3f 毫秒\n", dft*1000.0); 51 } while (dft * 1000 < millsecond); 52 //结束时用时 53 //printf("实际用时: %.3f 毫秒\n", dft*1000.0); 54 return dft*1000.0; 55 56 } 57 58 59 60 int _tmain(int argc, _TCHAR* argv[]) 61 { 62 63 64 double time = MyDelay(45); 65 printf("实际延时时间:%.3f\n", time); 66 67 68 //测试一: 69 //记录时间 70 vector<double> record; 71 72 LARGE_INTEGER ts, te, tc; 73 double ds, de; 74 LONGLONG qts, qte; 75 //获取时钟频率 76 QueryPerformanceFrequency(&tc); 77 ds = (double)tc.QuadPart; 78 79 for(int i=0;i<50;++