2016-06-15 37 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); 
}