Home > Back-end >  Call a block of code once every 10ms in a while loop without stopping the loop c
Call a block of code once every 10ms in a while loop without stopping the loop c

Time:11-21

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)
}

CodePudding user response:

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).

  • Related