Windows下的高精度定时器实现及精确时刻获取
2010年06月30日
通讯、VOIP、视频等领域的很多核心技术对时间精度的要求非常高,比如数据采集、时间同步、媒体流平滑控制、拥塞算法等等,很多技术都是以毫秒为单位来进行计算和控制的。但是Windows设计之初并不是以实时系统为目标的,所以Windows系统的时间精度一直不高,实际最小单位是15ms左右,导致的结果就是所有Windows的时间、线程相关的操作都无法以1ms来实现精确控制。
受影响的操作包括Sleep、GetTickCount、_ftime等等。比如你调用Sleep(2),期待2ms之后线程自动唤醒,但是实际结果可能是15ms甚至2x ms的时候才会唤醒,对于简单应用来说影响不大,但是对于精度要求非常高的系统来说,这样的问题就是非常致命的了。
代码思路如下:
1、高精度定时器。使用Singleton模式挂起请求Sleep的线程并统一管理,后台使用Windows MultiMedia SDK的定期回调函数不断检测并回复到时的线程,超时时间与当前时间采用QueryPerformanceCounter/QueryPerformanceFrequency的高精度计时,确保整体功能可靠性。
2、精确时刻获取。由于可以获取到毫秒级别的_ftime与GetTickCount都受到Windows系统时间精度影响,最小单位只有15ms,所以需要借助QueryPerformanceCounter/QueryPerformanceFrequency进行准确计时。代码首先根据_ftime获取起始时刻的精确刻度,然后根据差量计算当前的精确时刻。
代码中的Singleton模式可以找到很多实现,因此本文不进行详述
代码(VS2005 c++编译)
1、高精度定时器 #pragma once #include #include #include namespace akumaslab{ namespace time{ using std::list; class PreciseTimerProvider { struct WaitedHandle{ HANDLE threadHandle; LONGLONG elapsed;//超时时间 } ; typedef list handle_list_type; typedef akumaslab::system::Singleton timer_type; public: PreciseTimerProvider(void):highResolutionAvailable (false), timerID(0) { InitializeCriticalSection(&critical); static LARGE_INTEGER systemFrequency; if(0 != QueryPerformanceFrequency(&systemFrequency)) { timeBeginPeriod(callbackInterval); highResolutionAvailable = true; countPerMilliSecond = systemFrequency.QuadPart/1000; timerID = timeSetEvent(callbackInterval, 0, &PreciseTimerProvider::TimerFunc, NULL, TIME_PERIODIC); } } //挂起当前线程 //@milliSecond:超时时间,单位:毫秒 bool suspendCurrentThread(int milliSecond) { if(milliSecond = waited.elapsed) { ResumeThread(waited.threadHandle); ir = waitList.erase(ir); continue; } ir++; } LeaveCriticalSection(&critical); } ~PreciseTimerProvider(){ if (0 != timerID) { timeKillEvent(timerID); timerID = 0; timeEndPeriod(callbackInterval); } DeleteCriticalSection(&critical); } private: static void CALLBACK TimerFunc(UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2) { static bool initialed = false; if (!initialed) { if (initialWorkThread()) { initialed = true; } else{ return; } } timer_type::getRef().resumeTimeoutThread(); } //调整定时器工作线程优先级 static bool initialWorkThread() { HANDLE realProcessHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, _getpid()); if (NULL == realProcessHandle) { return false; } if (0 == SetPriorityClass(realProcessHandle, REALTIME_PRIORITY_CLASS)) { CloseHandle(realProcessHandle); return false; } HANDLE currentThreadHandle = GetCurrentThread(); HANDLE currentProcessHandle = GetCurrentProcess(); HANDLE realThreadHandle(0); DuplicateHandle(currentProcessHandle, currentThreadHandle, currentProcessHandle, &realThreadHandle, 0, FALSE, DUPLICATE_SAME_ACCESS); SetThreadPriority(realThreadHandle, THREAD_PRIORITY_TIME_CRITICAL); //必须关闭复制句柄 CloseHandle(realThreadHandle); CloseHandle(realProcessHandle); return true; } private: const static int callbackInterval = 1; CRITICAL_SECTION critical; MMRESULT timerID; LONGLONG countPerMilliSecond; bool highResolutionAvailable; handle_list_type waitList; }; class PreciseTimer { typedef akumaslab::system::Singleton timer_type; public: static bool wait(int milliSecond) { //static PreciseTimerProvider timer; return timer_type::getRef().suspendCurrentThread(milliSec ond); } }; } } DEMO int interval = 1; int repeatCount = 50; cout #include #include #include namespace akumaslab{ namespace time{ struct HighResolutionTime { int year; int month; int day; int hour; int min; int second; int millisecond; }; class CurrentTimeProvider { public: CurrentTimeProvider():highResolutionAvailable(fals e), countPerMilliSecond(0), beginCount(0) { static LARGE_INTEGER systemFrequency; if(0 != QueryPerformanceFrequency(&systemFrequency)) { highResolutionAvailable = true; countPerMilliSecond = systemFrequency.QuadPart/1000; _timeb tb; _ftime_s(&tb); unsigned short currentMilli = tb.millitm; LARGE_INTEGER now; QueryPerformanceCounter(&now); beginCount = now.QuadPart - (currentMilli*countPerMilliSecond); } }; bool getCurrentTime(HighResolutionTime& _time) { time_t tt; ::time(&tt); tm now; localtime_s(&now, &tt); _time.year = now.tm_year + 1900; _time.month = now.tm_mon + 1; _time.day = now.tm_mday + 1; _time.hour = now.tm_hour; _time.min = now.tm_min; _time.second = now.tm_sec; if (!highResolutionAvailable) { _time.millisecond = 0; } else{ LARGE_INTEGER qfc; QueryPerformanceCounter(&qfc); _time.millisecond = (int)((qfc.QuadPart - beginCount)/countPerMilliSecond)%1000; } return true; } private: bool highResolutionAvailable; LONGLONG countPerMilliSecond; LONGLONG beginCount; }; class CurrentTime { public: static bool get(HighResolutionTime& _time) { return akumaslab::system::Singleton::getRef().getCurrentTime(_time); } }; } } DEMO: HighResolutionTime time; CurrentTime::get(time); const int size = 20; char buf[size] = {0}; _snprintf_s(buf, size, size, "%02d:%02d %02d:%02d:%02d.%03d ", time.month, time.day, time.hour, time.min, time.second, time.millisecond); 测试结果如下,下图是高精度计时器按1ms进行Sleep的结果,左侧为使用_ftime计时,右侧为使用精确时刻计时,总体来说,虽然无法达到100%可靠,但是相对原来的15ms已经有较大提升,期望Windows能够尽快提供真正的高精度时间管理技术
发表评论
-
VC6应用WMI获取系统信息
2012-01-20 09:31 1036VC6应用WMI获取系统信息 2011年05月02日 花 ... -
Windows Installer的简单应用
2012-01-20 09:31 701Windows Installer的简单应 ... -
在android 2.3 AVD 模拟器上安装 google market 安卓市场
2012-01-20 09:31 597在android 2.3 AVD 模拟器上安装 google ... -
在android 2.3 AVD 模拟器上安装 google market 安卓市场
2012-01-20 09:31 585在android 2.3 AVD 模拟器上安装 google ... -
载沣:“瑜伽王爷”的柔软身段(二)
2012-01-19 14:33 525载沣:“瑜伽王爷”的柔软身段(二) 2012年01月09日 ... -
论外格用舍
2012-01-19 14:33 595论外格用舍 2012年01月13日 二十二、论外格用舍 ... -
中国人的用餐礼仪~~~有空大家看看,蛮受用的哦
2012-01-19 14:33 621中国人的用餐礼仪~~~有空大家看看,蛮受用的哦 2009年0 ... -
一代天骄成吉思汗的秘葬
2012-01-19 14:33 627一代天骄成吉思汗的秘 ... -
《论语》解读之3-19《使下以礼事上以忠》
2012-01-19 14:33 656《论语》解读之3-19《使下以礼事上以忠》 2011年12月 ... -
Flex动态创建类对象
2012-01-17 04:21 660Flex动态创建类对象 2010年08月07日 自Act ... -
107条Javascript的常用语句
2012-01-17 04:21 476107条Javascript的常用语句 2010年12月31 ... -
学习JavaScript---对象
2012-01-17 04:21 523学习JavaScript---对象 2010年10月01日 ... -
JavaScript内置对象
2012-01-17 04:20 467JavaScript内置对象 2010年11月01日 ... -
JS学习---ECMAScript对象
2012-01-17 04:20 606JS学习---ECMAScript对象 2010年11月25 ... -
女性最为吸引人的品质
2012-01-16 03:10 446女性最为吸引人的品质 2009年10月11日 ... -
现代女性怎样说话才可爱
2012-01-16 03:10 722现代女性怎样说话才可 ... -
流利口语脱口而出第九课
2012-01-16 03:10 564流利口语脱口而出第九课 2009年10月13日 第九课 ... -
女性恋爱时在意的11件事情
2012-01-16 03:10 538女性恋爱时在意的11件事情 2009年07月31日 如果 ... -
女性最为吸引人的品质
2012-01-16 03:10 436女性最为吸引人的品质 ...
相关推荐
同时,多线程环境下,为了减少线程间竞争和上下文切换带来的额外开销,可以使用异步I/O或信号量等机制,配合高精度定时器,实现高效的时间片调度和任务切换。这样,即使在高并发的情况下,也能保持系统的响应速度和...
在Windows操作系统中,获取精确时间间隔是编程中的一个重要任务,特别是在需要高精度计时的领域,如游戏开发、科学计算或者性能分析。标题提到的"获取精确时间间隔的方法"主要涉及的是Windows API中的一个关键函数...
"Timer计时器可以精确到毫秒"这个标题涉及到的是如何在VC++环境下创建一个能够提供高精度计时功能的定时器。在Windows操作系统中,通过调用特定的API函数,我们可以实现对时间的毫秒级甚至微秒级测量。 首先,`...
为了实现这一目标,Windows操作系统提供了一系列API函数,其中`QueryPerformanceFrequency`与`QueryPerformanceCounter`是两个核心函数,用于获取高精度的计时器频率以及当前计时器值。这两个函数常被用于测量代码段...
2. **高精度计时API**:在不同的操作系统中,有专门的API供开发者获取微秒甚至纳秒级别的高精度时间,如Unix/Linux的`gettimeofday()`、`clock_gettime()`,Windows的`QueryPerformanceCounter()`等。 3. **时间戳...
通过对计时器对象的性能测试,我们可以更好地理解和优化在MATLAB中使用定时任务的场景,特别是在需要高精度时间控制的应用中。通过分析这个脚本,开发者可以学习如何调试和评估计时器的性能,从而提升MATLAB程序的...