0

The following function is run consecutively:

void MyClass::handleTriggered(float dt)
{
    // dt is time interval (period) between current call to this function and previous one
}

dt is something like 0.0166026 seconds (comes from 60 frames per second).

I intend to do something every 0.25 seconds. Currently I'm using the fact that we are at 60 fps, i.e. function call occurs 60 times each second:

    static long int callCount = 0;
    ++callCount;
    // Since we are going with 60 fps, then 15 calls is 1/4 i.e. 0.25 seconds
    if (callCount % 15 == 0)
        // Do something every 0.25 seconds (every 15 calls)

Now I wonder how I can do it another way, with float types rather than int:

    static float sumPeriod = 0.0;
    // Total time elapsed so far
    sumPeriod += dt;
    if (/* How to compose the condition? */) {
        // Every 0.25 seconds do something
    }
Megidd
  • 7,089
  • 6
  • 65
  • 142
  • Simply sleep for 0.25 every time you finish doing that once: https://en.cppreference.com/w/cpp/thread/sleep_for – FlatAssembler Apr 15 '20 at 11:04
  • Seems like this is more of a hardware interrupt problem. Sleeping for `0.25` seconds will give you two issues (i) that's a minimum, (ii) the code will not run every `0.25` seconds due to the actual code itself taking time to run. – Bathsheba Apr 15 '20 at 11:06
  • 3
    This isn't strictly what you're asking, but using floating point for intervals is problematic - specifically, cumulative error and rounding will both cause missed triggers after some number of intervals. Just count integer microseconds or nanoseconds instead. – Useless Apr 15 '20 at 11:06
  • you wont get exact timing and then it depends what is more important to you: total time for N periods should be as exactly as possible N*0.25 / time between two invocations should never be less / more than 0.25 / other requirements – 463035818_is_not_an_ai Apr 15 '20 at 11:11

2 Answers2

1

You have to sum up the dt's and when they hit 0.25 you subtract 0.25 from the sum and do your thing.

static float sum = 0.0;
sum += dt;
if(sum > 0.25) {
    sum -= 0.25;
    // Do what you want to do every 0.25 secs here.
}
QuantumDeveloper
  • 737
  • 6
  • 15
-1
static float sumPeriod = 0.0;
// Total time elapsed so far
sumPeriod += dt;
if (sumPeriod > 0.25) {
    sumPeriod -= 0.25 * int(sumPeriod / 0.25);
    // Every 0.25 seconds do something
}
D34DStone
  • 47
  • 5
  • We don't use C style casts in C++, for some good reasons why see [this](https://stackoverflow.com/a/528009/12448530) answer – Object object Apr 15 '20 at 11:36
  • What is the point of `sumPeriod` here, it looks like you're just incrementing it and not using it. – T_Bacon Apr 15 '20 at 11:36