查看完整版本: [--
Qt之高精度多媒体定时器
--]
QTCN开发网
->
Qt 作品展
->
Qt之高精度多媒体定时器
[打印本页]
登录
->
注册
->
回复主题
->
发表主题
核心科技
2018-01-30 21:29
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();
yangyu52009
2018-01-31 19:58
编译需要 去掉 friend 之后的 WINAPI,并且链接 库Winmm
LIBS += -lWinmm
liuchangyin
2018-02-02 10:13
ms级的精度,windows比较难达到,DOS好像可以
核心科技
2018-02-03 22:12
liuchangyin
:
ms级的精度,windows比较难达到,DOS好像可以
(2018-02-02 10:13)
没问题,我试过,没问题的。我用10毫秒记录数据,没问题的。一秒钟记录一百条数据妥妥的。
x85371169
2018-02-05 15:44
QTimer设置精度后,准确性也是非常高的。当然了,同时开多个定时器会有影响
fearlazy
2018-02-27 14:26
liuyuanan
2018-03-03 13:19
这个不能跨平台
查看完整版本: [--
Qt之高精度多媒体定时器
--] [--
top
--]
Powered by
phpwind
v8.7
Code ©2003-2011
phpwind
Gzip disabled