是否可以创建一个在循环中跳过功能的计时器?

时间:2019-02-12 13:37:54

标签: c++ timer chrono chronometer

在我的项目中,我正在使用opencv从网络摄像头捕获帧并通过一些功能检测其中的某些内容。问题在于,在一个确定的函数中不必捕获所有帧,例如,每0.5秒获取一个帧就足够了,如果时间还没有结束,则循环继续执行下一个函数。代码中的想法是:

while(true){
  //read(frame)
  //cvtColor(....)
  // and other things
  time = 0;// start time
  if (time == 0.5){
      determinatefunction(frame, ...)
  }else {
      continue;
  }
  //some others functions
}

我试图用chrono库做与上述类似的事情:

// steady_clock example
#include <iostream>
#include <ctime>
#include <ratio>
#include <chrono>

using namespace std;

void foo(){
cout << "printing out 1000 stars...\n";
  for (int i=0; i<1000; ++i) cout << "*";
  cout << endl;
}

int main ()
{
    using namespace std::chrono;

    steady_clock::time_point t1 = steady_clock::now();
    int i = 0;
    while(i <= 100){
        cout << "Principio del bucle" << endl;
        steady_clock::time_point t2 = steady_clock::now();
        duration<double> time_span = duration_cast<duration<double>>(t2 - t1);
        cout << time_span.count() << endl;
        if (time_span.count() == 0.1){
            foo();
            steady_clock::time_point t1 = steady_clock::now();
        }else {
            continue;
        }
        cout << "fin del bucle" << endl;
        i++;
    }
}

但是循环永远不会结束,永远不会启动foo()函数。

我不能使用posix线程(我看到了sleep_for函数),因为我正在使用g ++(x86_64-win32-sjlj-rev4,由MinGW-W64项目构建)4.9.2及其与opencv 2.4.9一起使用。我尝试使用opencv实现mingw posix,但是当正确编写include和libs时,它给我的错误像'VideoCapture' was not declared in this scope VideoCapture cap(0)一样没有意义。

我正在使用Windows 7。

1 个答案:

答案 0 :(得分:3)

在大多数情况下,结合使用==和浮点计算是错误的。

不能保证在差异恰好为duration_cast<duration<double>>(t2 - t1)时执行0.1

相反,它可能类似于0.099324,并且在下一个迭代0.1000121

改为使用>=并在t1中定义另一个if并没有多大意义。

if (time_span.count() >= 0.1) {
  foo();
  t1 = steady_clock::now();
}