在定义的时间后退出c ++循环 [英] Exit a c++ loop after defined amount of time

查看:49
本文介绍了在定义的时间后退出c ++循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行一个循环并在2分钟后退出该循环.

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;
  }
}

推荐答案

最佳方式取决于您对解决方案的重视程度.通常,最好的方法是最简单的方法.最简单的解决方案是以下算法:

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:

  • 存储当前时间
  • 循环
    • 如果当前时间大于存储时间+ 2分钟
      • 打破循环

      这篇关于在定义的时间后退出c ++循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆