启动计时器并在3秒后重置

时间:2016-06-15 23:02:20

标签: c++

我想实现一个计时器,如果条件为真,则启动,3秒后我希望它重置计时器,它不会开始计数直到if语句中的条件再次为真。请参阅下面的代码:

//--here I want to check if 3 sec has gone, and if yes, do something and reset it--
int duration;
std::clock_t start;

while (1) {
     //some things here

     for (something) {
          //some things happening here

         if (a Condition) {
              start = std::clock(); <- start the timer here
         }
     }
}

我将使用视频流(opencv),这就是为什么我有while循环,以防你想知道。经过几次尝试,我没有成功。

我能够启动计时器但是我想要一个if语句来检查是否已经过了3秒duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;但是我仍然无法解决它(两者都要检查时间是否已经过去然后到重置它)。任何想法将不胜感激!

1 个答案:

答案 0 :(得分:2)

尝试这样的事情:

const std::clock_t notrunning = (std::clock_t)(-1);

inline void checkTimerReset(std::clock_t &start)
{
  if (start != notrunning) {
    if (((std::clock() - start) / CLOCKS_PER_SEC) >= 3)
      start = notrunning;
  }
}

...

std::clock_t start = notrunning;

while (1) {
  some things here

  for (something) {
    some things happening here

    if (something) {
      if (start == notrunning) {
          start = std::clock();
      }
    }

    checkTimerReset(start);
  }

  checkTimerReset(start);
}