核心科技 |
2018-01-30 21:25 |
Qt之高精度多媒体定时器
当前有许多工程实例需要非常准确的毫秒定时器,然而Qt多提供的QTimer定时器优先级较低,所以其准确性不能满足需求,故鲲鹏同志学习widows中的多媒体定时器自定义了一个高性能定时器的类,经过验证该定时器完全满足需要,且精度为1ms级(如果操作系统中安装的软件少)。本定时器经过实际工控项目时间得知10ms完全没问题,1ms没有试验过。
自定义定时器类
.h文件
#ifndef PERFORMANCETIMER_H #define PERFORMANCETIMER_H #include <QObject> #include <windows.h> class PerformanceTimer : public QObject { Q_OBJECT public: explicit PerformanceTimer(QObject *parent = 0); ~PerformanceTimer(); signals: void timeout(); public slots: void start(int timeInterval); void stop(); friend WINAPI void CALLBACK PeriodCycle(uint,uint,DWORD_PTR,DWORD_PTR,DWORD_PTR); private: int m_interval; int m_id; }; #endif // PERFORMANCETIMER_H
.cpp文件
#include "performancetimer.h" #ifdef __MINGW32__ #define TIME_KILL_SYNCHRONOUS 0x0100 #endif void CALLBACK PeriodCycle(uint timerId,uint,DWORD_PTR user,DWORD_PTR,DWORD_PTR) { PerformanceTimer *t=reinterpret_cast<PerformanceTimer *>(user); emit t->timeout(); } PerformanceTimer::PerformanceTimer(QObject *parent) : QObject(parent) { m_id=0; } PerformanceTimer::~PerformanceTimer() { stop(); } void PerformanceTimer::start(int timeInterval) { m_id=timeSetEvent(timeInterval,1,PeriodCycle,(DWORD_PTR)this,TIME_CALLBACK_FUNCTION|TIME_PERIODIC|TIME_KILL_SYNCHRONOUS); } void PerformanceTimer::stop() { if(m_id) { timeKillEvent(m_id); m_id=0; } }
使用方法
使用方法是按照以上代码完成该自定义类,然后在其他需要定时器的地方写入代码,声明一个定时器对象,然后使用该定时器的信号timeout()绑定需要的槽函数,然后根据不同的条件开始或者结束该时钟,具体代码如下: PerformanceTimer *timer=new PerformanceTimer(this); connect(timer,SIGNAL(timeout()),this,SLOT(slotFuction())); timer->start(20); //20为毫秒 或者timer->stop(); |
|