如何在c ++中实现计时器

时间:2013-11-06 18:53:09

标签: c++ linux timer

我正在研究手势识别应用程序,我想实现计时器,但我不知道如何。

这就是我想要做的事情:用户应该在下一个功能发生之前显示一个手势3秒。

现在看起来像这样:

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;

我希望它是这样的:if(left_index==1)< - 如果这是真的3秒而不是{}发生。

谢谢你的帮助。

4 个答案:

答案 0 :(得分:1)

有一个名为sleep的内置函数。这将使你的程序在int x毫秒内保持静止

我将使函数wait(int seconds):

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

等待(1); //等待1秒或1000毫秒

答案 1 :(得分:0)

此外,您可以尝试执行以下操作:

#include <time.h>

clock_t init, final;

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

请查看这些链接以获取进一步参考:

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

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

答案 2 :(得分:0)

您可以尝试以下方法:

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

对于,我更倾向于使用来自std::chrono的类的解决方案,而不是使用time.h

答案 3 :(得分:0)

假设您的应用正在运行更新循环。

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

这是基本逻辑,您可以编写一个计时器类并将正文重构为一个函数,为您的应用程序的其他部分腾出空间。

相关问题