2016-06-15 39 views
0

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

//--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;但我仍然无法解决它(既检查时间是否已经过去,然后重置它) 。任何想法将不胜感激!

回答

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