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

Is there a way to call a function n times per second while compensating for drift?

I’ve seen a lot of answers to very similar questions, but they all seem to resort to using something like a sleep(1/n) call at the end of a function or in some cases timing the function and calling sleep((1/n) – functionTime). Surely there is a better way to do this? Modern hardware has access to precise hardware timers that can send an interrupt to the CPU some known number of times per second, is there no way to take advantage of these timers to run a function such as a physics engine update a known, fixed number of times per second from user space code? What I would like to do in particular is, preferably in C or C++, define some function, let’s call it foo(), and designate it to be called N times per second. I would want to be able to know that if M seconds have passed, foo will have been called N*M times assuming foo() ran in less than 1/N seconds on average.

>Solution :

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

There is no standard C API for scheduling calls.

You probably want to have a separate thread that runs every 1/Nth of a second.

In the pthreads world, this can be done with pthread_cond_timedwait. This function expects the absolute time to wake up. In addition, some other thread can wake it up using the condition variable if some unplanned update needs to be made.

In the Windows world you probably need one of the WaitFor<whatever> functions. They expect a relative timeout, so you want to convert absolute time to relative time-interval-from-now yourself. In this case, too, another thread is able to wake you up to perform an urgent update.

The absolute time you need is just the absolute time the previous call was scheduled for, plus 1/Nth of a second. The very first one can be set to the current time just before the call.

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