是否可以创建一个跳过循环中函数的计时器

Is it possible to create a timer that skips a function within a loop?

本文关键字:循环 函数 计时器 一个 创建 是否      更新时间:2023-10-16

在我的项目中,我使用 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
}

我尝试用时间库做一些类似于上面的事情:

// 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,但它给了我一些没有意义的错误,例如当正确编写包含和库时'VideoCapture' was not declared in this scope VideoCapture cap(0)

我正在使用视窗 7。

==与浮点计算结合使用大多数时候是错误的。

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

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

请改用>=,在if中定义另一个t1没有多大意义。

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