Skip to content
Advertisement

Control loop time with usleep

I try to make sure the execution time of each loop to 10ms with usleep , but sometimes it exceeds 10ms.

I have no idea how to solve this problem, is it proper to use usleep and gettimeofday in this case?

Please help my find out what i missed.

Result: 0.0127289 0.0136499 0.0151598 0.0114031 0.014801

JavaScript

Advertisement

Answer

To keep the loop overhead (which is generally unknown) from constantly accumulating error, you can sleep until a time point, instead of for a time duration. Using C++’s <chrono> and <thread> libraries, this is incredibly easy:

JavaScript

One can dress this up with more calls to steady_clock::now() in order to ascertain the time between iterations, and perhaps more importantly, the average iteration time:

JavaScript

Above I’ve added to the loop overhead by doing more things within the loop. However the loop is still going to wake up about every 10ms. Sometimes the OS will wake the thread late, but next time the loop automatically adjusts itself to sleep for a shorter time. Thus the average iteration rate self-corrects to 10ms.

On my machine this just output:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement