是否可以创建一个跳过循环中函数的计时器
Is it possible to create a timer that skips a function within a loop?
在我的项目中,我使用 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();
}
相关文章:
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 循环中的随机函数
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 未在函数C++中执行的循环
- 如何在没有可变参数函数的情况下循环函数的参数
- 循环函数中的并行数组
- 如何循环函数,直到新的 mqtt 消息到达
- 循环C++ R 函数
- 为什么我的 while 循环函数只返回"1"?
- Pthread 循环函数永远不会被调用
- 循环函数调用未正确循环!(C++)
- 对于循环函数参数在C++中的奇数
- 具有双重调度的C++多态循环函数
- 循环函数给出"return’ with a value, in function returning void"误差
- 如何用循环函数求和
- 如何使c++中的for each循环函数与自定义类一起工作
- c++分割故障及循环函数
- C++ |需要帮助从 for 循环函数转换 - >递归函数
- 为什么要在 levelDB 的缓存中使用 while 循环(函数 Resize)?
- odeint中的循环函数