Search code examples
c++timing

What is the recommended or most precise way, to call a function after a specific time?


I wrote a little program to launch and record a stereo setup of cameras. I would like to record a sequence of 100ms. The thing is: I don't know how to time the functions with the highest possible precision. I found the header <unistd.h> which includes the function usleep which can pause the execution for a specified microsecond interval. So in my program I'm doing something like this:

left_camera.start_recording();
right_camera.start_recording();
usleep(100000);
left_camera.stop_recording();
right_camera.stop_recording();

Is there a better way to ensure precise timing between the two functions?


Solution

  • You can also use std::this_thread::sleep_for (C++11)

    #include <chrono>
    #include <thread>
    
    int main()
    {
        std::this_thread::sleep_for(std::chrono::nanoseconds(500));
    }