3

I would like to execute a loop and exit this loop after let's say 2 minutes.

while(condition) { // do stuff // exit this loop after 2 minutes } 

Could someone recommend me the best way to do this ?

Based on the answers, here is what I did :

time_t futur = time(NULL) + 120; while(condition) { // do stuff if(time(NULL) > futur) { break; } } 
5

2 Answers 2

3

Best way depends on what things you value more about a solution. Usually the best way is the simplest way. The simplest solution is following algorithm:

  • store the current time
  • loop
    • if current time is greater than stored time + 2 min
      • break out of loop
    • do stuff
Sign up to request clarification or add additional context in comments.

Comments

2

Use clock() from time.h and calculate time passed, such as:

timeStart = clock(); while (condition) { if ((clock() - timeStart) / CLOCKS_PER_SEC >= 120) // time in seconds break; } 

2 Comments

clock() measures CPU time, which doesn't sound like what "after 2 minutes" is looking for; std::time() measures wall clock time. And the value returned by clock() is not necessarily in milliseconds; you have to multiply it by CLOCKS_PER_SEC to convert it to seconds.
And you got it right, dividing by CLOCKS_PER_SEC despite my claim that you have to multiply. <g>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.