简体   繁体   中英

how to implement timer in c++

i'm working on gesture recognition application and i would like to implement timer but i don't know how.

here is what i want to do: user should be showing one gesture for 3 seconds before next function happens.

now it looks like this:

if(left_index==1)                 
{
putText("correct",Point(95,195),FONT_HERSHEY_COMPLEX_SMALL,0.8,Scalar(0,255,0),1,CV_AA);
correct = true;
}
break;

i would like it to be like this: if(left_index==1) <- if this is true for 3 seconds than the {} happens.

thank you for help.

there is a built-in function called sleep. It will kind of put your program at rest for int x milliseconds

I will make a function wait(int seconds):

void wait(long seconds)
{
    seconds = seconds * 1000;
    sleep(seconds);
}

wait(1); //waits for 1 second or 1000 milliseconds

Also, you can try doing the following :

#include <time.h>

clock_t init, final;

init=clock();
//
// do stuff
//
final=clock()-init;
cout << (double)final / ((double)CLOCKS_PER_SEC);

Check these links out for further reference :

http://www.cplusplus.com/forum/beginner/317/

http://www.cplusplus.com/reference/ctime/

You could try the following:

#include <time.h>
#include <unistd.h>

// Whatever your context is ...
if(left_index==1)
{
    clock_t init, now;

    init=clock();
    now=clock();
    while((left_index==1) && ((now-init) / CLOCKS_PER_SEC) < 3))
    {
        sleep(100); // give other threads a chance!
        now=clock();
    }
    if((left_index==1) && (now-init) / CLOCKS_PER_SEC) >= 3))
    {
        // proceed with stuff
        putText
          ( "correct"
          , Point(95,195)
          , FONT_HERSHEY_COMPLEX_SMALL,0.8,Scalar(0,255,0),1,CV_AA);
        correct = true;        
    }
}

For I'd prefer a solution involving the classes from std::chrono instead working with time.h .

assuming your app is running an update loop.

bool gesture_testing = false;
std::chrono::time_point time_start;

while(app_running) {
  if (! gesture_testing) {
    if (left_index == 1) {
      gesture_testing = true;
      time_start = std::chrono::high_resolution_clock::now();
    }
  } else {
    if (left_index != 1) {
      gesture_testing = false;
    } else {
      auto time_end = std::chrono::high_resolution_clock::now();
      auto duration = std::chrono::duration_cast<std::chrono::seconds>(time_end - time_start);
      if (duration.count() == 3) {
        // do gesture function
        gesture_testing = false;
      }
    }
  }
}

this is the basic logic, you can write a timer class and refactor the body into one function to make room for other part of your app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM