使用中发现QTimer准确性不是太高,于是在windows中做了简单测试
定时10ms
定时20ms
定时30ms
定时40ms
定时50ms
定时100ms
替代方案:windows多媒体计时器
#include "MMTimer.h"
#include <MMSystem.h>
#ifdef __MINGW32__ //w32api bug
#define TIME_KILL_SYNCHRONOUS 0x0100
#endif
#pragma comment( lib, "winmm.lib" )
void WINAPI CALLBACK mmtimer_proc(uint timerId, uint, DWORD_PTR user, DWORD_PTR, DWORD_PTR)
{
MMTimer *t = reinterpret_cast<MMTimer*>(user);
emit t->timeout();
}
MMTimer::MMTimer(QObject *parent)
: QObject(parent)
, m_interval(0)
, m_id(0)
{
}
MMTimer::~MMTimer()
{
stop();
}
void MMTimer::start(int msinterval)
{
m_id = timeSetEvent(msinterval, 1, mmtimer_proc, (DWORD_PTR)this,
TIME_CALLBACK_FUNCTION | TIME_PERIODIC | TIME_KILL_SYNCHRONOUS);
}
void MMTimer::stop()
{
if (m_id)
{
timeKillEvent(m_id);
m_id = 0;
}
}
测试结果
定时10ms
定时20ms
定时30ms
定时40ms
定时50ms
定时100ms
从测试结果来看,在开始的大约前300ms计时是有问题的,我也不知道原因,不过问题不大,总体来说这个精度还是足够使用了。