Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Call a block of code once every 10ms in a while loop without stopping the loop c++

So I’m trying to run a block of code once every 10ms in a while loop without stopping the loop (sleeping).

I would like to achieve something like this:

while (true) {
    if (should_run_the_10ms_code) {
        // some code (once every 10 ms)
    }

    // some other code (every tick)
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

std::chrono::steady_clock::now gives you the current time from a monotonic clock. Here is a relatively simple way to use it:

auto timer = std::chrono::steady_clock::now();
while (true) {
    auto now = std::chrono::steady_clock::now();
    std::chrono::duration<double, std::milli> timer_diff_ms = timer - now;
    if (timer_diff_ms >= 10.0) {
        // some code (once every 10 ms)
        timer = now;
        // or
        // timer = std::chrono::steady_clock::now();
        // if the "some code" takes a bit of time
    }

    // some other code (every tick)
}

Note that timer_diff_ms might be much greater than 10 if something lenghty happens between the now() calls (might be in the "some other code" part, might be completely unrelated to your program).

You can also use std::chrono::milliseconds instead of std::chrono::duration<double, std::milli> if you don’t need a double (it will be some integer type).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading