使用QT定时器遇到的问题

问题描述:
程序上有槽函数触发频率变化的需求。在使用Qt定时器触发槽函数的过程中发现,每秒钟1000次没有问题,在每秒钟30~50次的情况下出现了延迟。
主体代码如下:

    std::chrono::time_point lastTime = std::chrono::high_resolution_clock::now();
    m_grabImgTimer = new QTimer();
    connect(m_grabImgTimer, SIGNAL(timeout()), this, SLOT(TriggerGrabImaSlot()));
    m_grabImgTimer->start(1000/ 30);
void TriggerGrabImaSlot()
{
    std::chrono::time_point nowTime = std::chrono::high_resolution_clock::now();

    std::chrono::duration<double, std::milli> fp_ms = nowTime - lastTime;
    lastTimer = nowTime;
    std::cout << fp_ms.count() << " ms"<<std::endl;
}

10次的时候控制台打印
使用QT定时器遇到的问题_第1张图片

30次的时候控制台打印
使用QT定时器遇到的问题_第2张图片
造成原因:
使用QT定时器遇到的问题_第3张图片
On UNIX (including Linux, macOS, and iOS), Qt will keep millisecond accuracy for Qt::PreciseTimer. For Qt::CoarseTimer, the interval will be adjusted up to 5% to align the timer with other timers that are expected to fire at or around the same time. The objective is to make most timers wake up at the same time, thereby reducing CPU wakeups and power consumption.
On Windows, Qt will use Windows’s Multimedia timer facility (if available) for Qt::PreciseTimer and normal Windows timers for Qt::CoarseTimer and Qt::VeryCoarseTimer.
On all platforms, the interval for Qt::VeryCoarseTimer is rounded to the nearest full second (e.g. an interval of 23500ms will be rounded to 24000ms, and 20300ms to 20000ms).
在这里插入图片描述
结论
对精度有一定要求,并且还要使用QT的定时器,那么在创建定时器的时候,需要更改一下时钟的类型。

m_grabImgTimer->setTimerType(Qt::PreciseTimer);

你可能感兴趣的:(QT,qt,开发语言,c++)