Important: Please read the Qt Code of Conduct -

Lots of QTimer [ SOLVED ]

  • Hello,
    I am working on an audio application which plays single music notes at different intervals.
    Each note object has a QTimer attribute and it is triggered only once when the note should be played (single shot).
    However, if I have a lot of notes, can this lead to very extensive CPU usage?
    What would be the best alternative to achieve that?


  • Moderators

    Well, you can definitely test and see the results. This does, however, seem to be a pretty resource-heavy solution.

    Why not try a different approach: a single QTimer, that repeatedly ticks at short intervals. For every tick, you check how much time has passed (with either QTimer or QDateTime) and play a note if it is needed.

  • Hello sierdzio,

    I will try your solution as well thank you.
    But as you mentioned it should tick at very short intervals.

  • Moderators

    Well, your graphic card creates full 1-2 mega pixels of content, 60 times a second. So a few music notes should not be much of a problem, really.

    Or you can try (I don't know your exact use case) to construct a MIDI track out of your notes, and then simply play the file using your sound card.

  • What about this solution: Do some pre-processing on your notes and convert them into a list of delays, from the first to to the last note. Then you just use a single QTimer, in "single shot" mode, to play the first note. Once that one is triggered, it will play the first note, pick the next delay from the list (i.e delay between first and second note) and then rearm the QTimer accordingly. Next time the timer is triggered, it plays the second note, fetches the next delay from the list and sets up the timer again (for the third note). And so on...


    BTW: I'm not sure QTimer has enough precision for this task. I mean, if you setup a QTimer to fire after N milliseconds, it means that it will wait at least N milliseconds before it fires. But it could take more than N milliseconds, e.g. because your application has more signals to process before the QTimer's signal or simply because your Process/Thread is not currently active...

  • Hello MuldeR,
    Thank you for your help as well. Will try this as well.
    The problem of precision is a good remark. I will need to do some testing anyways but from what I have read, it will sound oki if the interval between the time the note should be exactly played and the time it is effectively played is less than 50ms.

Log in to reply