0

I would like to call the doStuff() function at 50Hz. This is what I am doing now:

mTimer = new QTimer(this););
connect(mTimer, SIGNAL(timeout()), SLOT(doStuff()));
mTimer->start(20);

But the result is that doStuff() is only called around 30Hz. The doStuff() call itself might take some time (several ms, but always less than 20ms). What might be the problem here?

Nyaruko
  • 4,329
  • 9
  • 54
  • 105
  • 2
    Why are you making it a *single-shot* timer? – Some programmer dude Feb 23 '17 at 14:57
  • I have no clue about timers in programming, but maybe you could check every so often(every ms maybe) that if 20ms passed since the last call. But I would believe there are better solutions to this. – Kami Kaze Feb 23 '17 at 14:59
  • What behavior are you trying to get? If `doStuff()` on average takes more than the allotted time you will have to shorten it or use threads. If it takes a long time because of waiting for input concider using an async approach. – Nathaniel Johnson Feb 23 '17 at 15:01
  • 1
    If you are using Qt5, you can specify the timer time, which defines the accuracy of the timer. (http://doc.qt.io/qt-5/qt.html#TimerType-enum) The default value for timer type is Qt::CoarseTimer, which tries to keep the accuracy within 5% of the desired interval. In your case you are looking to use Qt::PreciseTimer. – ManuelH Feb 23 '17 at 15:02
  • Also, dump the SIGNAL and SLOT macros for the new functional style. – Nathaniel Johnson Feb 23 '17 at 15:02
  • Timers are inherently inaccurate (on systems where Qt is available). Regardless, the timer doesn't care, what is happening in between the timer intervals. If your `doStuff()` runs for 10 ms, it's not like the timer is postponed for that amount of time. – IInspectable Feb 23 '17 at 15:03
  • You can launch `setSingleShot` at the beginning of `doStuff` to start itself again in 1/50 seconds. – Yuriy Ivaskevych Feb 23 '17 at 15:04
  • For example, if the doStuff() is triggered (and we say it's now time 0), and it takes 10ms to finish. Will the next timeout() signal be triggered after 20ms or 30ms? – Nyaruko Feb 23 '17 at 15:10
  • 2
    If the timer is not a one-shot timer, your function should be called around every 20 millisecond, no matter how long the function executes. – Some programmer dude Feb 23 '17 at 15:17
  • 1
    @Someprogrammerdude has already provided the answer. Just to mention that the signal itself will be triggered every 20ms or whichever is the interval set. – N. Gerontidis Feb 23 '17 at 15:24

0 Answers0