Search code examples
c++timerc++-chronochronometer

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


In my project I'm using opencv to catch frames from a webcam and detect some things in there through some functions. The problem is that in a determinate function is not necesary to catch all the frames, it would be enough to take a frame every 0.5 seconds for example and if the time has not finished, the loop continue to the next function. The idea in code would be:

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

I tried to do something similar to the above with the chrono library:

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

But the loop never ends and never start foo() function.

I can't use posix thread(I saw the function sleep_for) because i'm using g++ (x86_64-win32-sjlj-rev4, Built by MinGW-W64 project) 4.9.2 and its works with opencv 2.4.9. I try to implement mingw posix with opencv but it give me errors that do not make sense like 'VideoCapture' was not declared in this scope VideoCapture cap(0) when the includes and libs are written correctly.

I'using windows 7.


Solution

  • Using == in combination with floating point calculations is most of the time wrong.

    There is no guarantee that duration_cast<duration<double>>(t2 - t1) will be executed when the difference is exactly 0.1.

    Instead it might be something like 0.099324 and in the next iteration 0.1000121

    Use >= instead and defining another t1 within the if does not make much sense.

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