Neil G Neil G - 2 months ago 12
C++ Question

What is the best way to exit out of a loop after an elapsed time of 30ms in C++

What is the best way to exit out of a loop as close to 30ms as possible in C++. Polling boost:microsec_clock ? Polling QTime ? Something else?

Something like:

A = now;
for (blah; blah; blah) {
Blah();
if (now - A > 30000)
break;
}


It should work on Linux, OS X, and Windows.

The calculations in the loop are for updating a simulation. Every 30ms, I'd like to update the viewport.

Answer

The code snippet example in this link pretty much does what you want:

http://www.cplusplus.com/reference/clibrary/ctime/clock/

Adapted from their example:

void runwait ( int seconds )
{
   clock_t endwait;
   endwait = clock () + seconds * CLOCKS_PER_SEC ;
   while (clock() < endwait)
   {
      /* Do stuff while waiting */
   }
}
Comments