How to Implement a Timer in C++ for Repeating Code Blocks

  • Context: Comp Sci 
  • Thread starter Thread starter jaydnul
  • Start date Start date
  • Tags Tags
    C++ Timer
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
5 replies · 2K views
jaydnul
Messages
558
Reaction score
15
Basically within my whole code is 4 major chunks of code that each loop repeatedly. The obvious problem is when I run it, it will get stuck on the first chunk and loop forever, therefore never moving on the next chunk. What I need is to have each section run for 10 seconds and then move on. Is there a simple function that could do this?

Thanks a bunch!
 
Physics news on Phys.org
why can't you restructure your code with a main loop so that you do one iteration for each of the four chunks?

or does the subsequent chunks depend on the first chunk to be completed?

As an example

Code:
for(int i=0; i<max; i++) {
   dochunk1(i)
   dochunk2(i)
    ...
}
 
I need more than one iteration from each chunk at a time. They are blinking LEDs and need to be blinking for a certain amount of time before moving on to the next LEDs (simplified but you get the idea).
 
How is your program determining how long 10 sec. is? What OS are you using? The reason I ask is that the OS might have some APIs that you can use to do this, which would probably be better than you having an empty loop run for a set amount of time that you determine by trial and error.
 
Hmm. Maybe not what people suggested. Would do the following (and maybe this is what you want):
Code:
unsigned char cur_loop = 0; // an index.
unsigned char loop_count = 4; // you have four loops.
long interval = 10000 // 10000, assuming milliseconds, stand for 10 seconds per loop.
long time = current_system_time(); // use whatever type best suits your needs (or the underlying implementation).
while (true) {
  if (current_system_time() - time > interval) {
    cur_loop = (cur_loop + 1) % loop_count;
  }
  switch (cur_loop) {
     // cases and their blocks here (the magic happens here!)
  }
}
// Be warned of the overhead of current_system_time()!
Copying and pasting this will not do much. I suggest C++11 and the chrono library. Read the documentation. Good luck.
If you need to repeat for n seconds then go ahead a sleep function won't work without multithreading (noob here, so I may be wrong).