1

I'm trying to write a loop that runs once every x milliseconds, is there a way to do something like this effectively in c++?

Hope someone could help me with an example how I would go about writing a loop like this

J. Grohmann
  • 391
  • 1
  • 6
  • 15
  • 3
    Needs dedicated hardware and/or OS support and/or a driver and/or something. Your requirement is way underspecified - we don't know if you can use a sleep() loop or need a hydrogen fountain clock. – Martin James Jan 17 '16 at 09:11

1 Answers1

1

One and the simplest approach would be using windows.h library's Sleep() function.

#include "windows.h" 
...
while(1) 
{
for(...) {} // your loop
Sleep(miliseconds);
if(something) { break; } // to prevent infinite looping.
}
...

A better solution would be using std::this_thread::sleep_for() from < thread > header. more documentation and examples here.

ddacot
  • 1,212
  • 3
  • 14
  • 40
  • This doesn't guarantee execution every n ms, it assumes no other code is ever run (the code that is being run takes time...) And the system provided sleep functions are not accurate. – Sami Kuhmonen Jan 17 '16 at 09:23
  • @SamiKuhmonen Agree. As i said using Sleep() function, would get the job done, however with some losses. The second solution i proposed is better and more accurate. – ddacot Jan 17 '16 at 09:26
  • Thanks, I remember Java and C# having a function that measures the time taken from a specific line to another and saves the time in a variable. Is there something similar for C++? – J. Grohmann Jan 17 '16 at 09:27
  • @ColdZer0 check the link i've provided on std::this_thread::sleep_for(), the example is exactly what you're asking right now. – ddacot Jan 17 '16 at 09:28