作者:戎亚新南京航空航天大学仿真与控制实验室
下载源代码 在开发 Windows 下的应用程序时,经常需要用的计时,尤其在一些对时间要求比较高的程序中,计时的精确性是很重要的,本文介绍了两种精确计时的方法,计时的精度可以达到ms级,而且可以认为它是精确的,可以在大多数情况下作为时间的基准。
用API函数::timeGetTime()获取从开机到现在经过的ms数,它的返回类型为DWORD类型,因此它的最大计时长度为2^32ms,约等于49天,::timeGetTime()是一个多媒体函数,所以它的优先级是很高的,一般可以将它看成是精确的。 用查询系统定时器的计数值的方法,用到的API函数是QueryPerformanceCounter、QueryPerformanceFrequency,方法是用当前计数值减去开始计时时刻的计数值,得到计数差值,再除以系统定时器的频率就是计的时间,通常系统定时器的频率非常高,我在 intel845e 的主板上达到了3579545hz,当然对于不同的主板,它的频率是不同的。程序运行的结果 如图一所示:图一这种计时方法要用另外一个线程专门来查询系统定时器的计数值,这就用到了多线程的知识。由于线程的调用是需要处理器时间的,所以在本中,多线程定时器的时间总要落后于多媒体定时器时间。但在中间的任何一个读取时间的时刻都是非常精确的,只是从读取到显示有一个延迟过程。 下面讲一下Windows高频事件的产生,还是利用上面两种方法,Windows下有一个多媒体定时器,用法为一组API函数的调用,它们是:
MMRESULT timeBeginPeriod( UINT uPeriod ) ; MMRESULT timeSetEvent( UINT uDelay, UINT uResolution, LPTIMECALLBACK lpTimeProc, DWORD dwUser, UINT fuEvent ); void CALLBACK TimeProc( UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2 ); MMRESULT timeKillEvent( UINT uTimerID ); MMRESULT timeEndPeriod( UINT uPeriod );其中timeBeginPeriod是用来设置最高定时精度的,最高精度为1ms,如果要产生间隔为1ms的中断,必须调用timeBeginPeriod(1);当定时器用完之后就要用timeEndPeriod(1);来恢复默认的精度。具体使用方法为在timeBeginPeriod(1)调用之后用timeSetEvent()注册一个回调函数,即一个中断处理过程。它还可以向回调函数传递一个参数,通常可以传送一个窗口句柄之类的东西。而回调函数TimeProc则从dwwUser参数中取出传递的参数使用。在Windows下,可以用这种方法进行1ms精度的定时数据采集,数据发送,但要保证1ms能完成所有的操作和运算。本人经过实践证明,用它来实现控制的精度是足够的。 第二种方法还是使用多线程查询系统定时器计数值,它与上面提到的方法相比有优点也有缺点,缺点是精度不够高,优点是产生的间隔能突破1ms的限制,可以达到更小的间隔,理论上事件产生的频率可以和系统定时器的频率一样。主要示例代码如下:
UINT Timer(LPVOID pParam) { QueryPerformanceCounter((LARGE_INTEGER *)& gl_BeginTime ); while(gl_bStart) { QueryPerformanceCounter((LARGE_INTEGER *)&gl_CurrentTime ); If(gl_CurrentTime - gl_BeginTime > 1.0/Interval ) { //定时的事件,比如发送数据到端口,采集数据等 gl_BeginTime = gl_CurrentTime; } } return 1; }这是多线程中的一个线程函数,Interval是产生事件的间隔,如果为0.001则为1ms产生一次,理论上如果Interval为1,则以最大的频率产生事件。即可以用Windows产生很高频率的事件,但是由于线程的调用是要有时间的,有的时候可能会造成这个线程一直没有得到执行,从而造成有一段时间没有进行计数,这段时间的定时事件就没有产生了,如果定时的频率越高,丢失的可能性就越大。但如果用它来产生高频随时间变化的随机信号还是很有价值的。这在实时仿真中尤其如此。具体的实现请参看详细的例子代码。如有疑问,请与我联系:qq:21881480email:bsrong@elong.com 或 bsrong_nuaa@msn.com
//Timer using Performance Counter #ifndef TIMER_H #define TIMER_H #include <iostream> #include <windows.h> class Timer { public: Timer(); ~Timer() {}; void start(); void end(); float getTime() const; void display() const; private: __int64 frequency; // Timer Frequency float resolution; // Timer Resolution unsigned long mm_timer_start; // Multimedia Timer Start Value unsigned long mm_timer_elapsed; // Multimedia Timer Elapsed Time bool performance_timer; // Using The Performance Timer? __int64 performance_timer_start; // Performance Timer Start Value __int64 performance_timer_elapsed; // Performance Timer Elapsed Time float startTime; float endTime; float passTime; }; Timer::Timer() { // Check To See If A Performance Counter Is Available // If One Is Available The Timer Frequency Will Be Updated if (!QueryPerformanceFrequency((LARGE_INTEGER *) & frequency)) { // No Performace Counter Available performance_timer = FALSE; // Set Performance Timer To FALSE //mm_timer_start = timeGetTime(); // Use timeGetTime() To Get Current Time resolution = 1.0f/1000.0f; // Set Our Timer Resolution To .001f frequency = 1000; // Set Our Timer Frequency To 1000 mm_timer_elapsed = mm_timer_start; // Set The Elapsed Time To The Current Time } else { // Performance Counter Is Available, Use It Instead Of The Multimedia Timer // Get The Current Time And Store It In performance_timer_start QueryPerformanceCounter((LARGE_INTEGER *) &performance_timer_start); performance_timer = TRUE; // Set Performance Timer To TRUE // Calculate The Timer Resolution Using The Timer Frequency resolution = (float) (((double)1.0f)/((double)frequency)); // Set The Elapsed Time To The Current Time performance_timer_elapsed = performance_timer_start; } } void Timer::start() { __int64 time; // time Will Hold A 64 Bit Integer if (performance_timer) // Are We Using The Performance Timer? { QueryPerformanceCounter((LARGE_INTEGER *) &time); // Grab The Current Performance Time // Return The Current Time Minus The Start Time Multiplied By The Resolution And 1000 (To Get MS) startTime = ( (float) ( time - performance_timer_start) * resolution)*1000.0f; } else { // Return The Current Time Minus The Start Time Multiplied By The Resolution And 1000 (To Get MS) //startTime = ( (float) ( timeGetTime() - mm_timer_start) * resolution)*1000.0f; } } void Timer::end() { __int64 time; // time Will Hold A 64 Bit Integer if (performance_timer) // Are We Using The Performance Timer? { QueryPerformanceCounter((LARGE_INTEGER *) &time); // Grab The Current Performance Time // Return The Current Time Minus The Start Time Multiplied By The Resolution And 1000 (To Get MS) endTime = ( (float) ( time - performance_timer_start) * resolution)*1000.0f; } else { // Return The Current Time Minus The Start Time Multiplied By The Resolution And 1000 (To Get MS) //endTime = ( (float) ( timeGetTime() - mm_timer_start) * resolution)*1000.0f; } passTime = endTime - startTime; } float Timer::getTime() const { return passTime/1000; } void Timer::display() const { std::cout < < "It takes " < < passTime/1000 < < " s. " < < std::endl; } #endif