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;
  }
}
klaus
  • 754
  • 8
  • 28
  • 1
    use std::chrono – Asesh Aug 29 '17 at 14:21
  • 1
    The most portable solution is to use the time keeping functionalities provided by [`std::chrono`](http://en.cppreference.com/w/cpp/chrono). – François Andrieux Aug 29 '17 at 14:21
  • 5
    Possible duplicate of [Running a function for specified duration : C++ with ](https://stackoverflow.com/questions/28768144/running-a-function-for-specified-duration-c-with-chrono) – LogicStuff Aug 29 '17 at 14:22
  • What should happen if after two minutes, the body is still executing? should execution just be cut off? – Luchian Grigore Aug 29 '17 at 14:22
  • Possible duplicate of [What is the best way to exit out of a loop after an elapsed time of 30ms in C++](https://stackoverflow.com/questions/946167/what-is-the-best-way-to-exit-out-of-a-loop-after-an-elapsed-time-of-30ms-in-c) – user1725145 Jul 18 '19 at 11:11

2 Answers2

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
eerorika
  • 232,697
  • 12
  • 197
  • 326
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;
}
Treyten Carey
  • 641
  • 7
  • 17
  • 1
    `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. – Pete Becker Aug 29 '17 at 14:41
  • And you got it right, dividing by `CLOCKS_PER_SEC` despite my claim that you have to multiply. – Pete Becker Aug 29 '17 at 15:45