Call an expensive function periodically inside a loop

140 views Asked by At

I call a computationally expensive function inside a loop:

for( int j = 0; j < Max; ++j ) {

    // ...

    processQueuedEvents(); // Computationally expensive call

    // ...

}

However, I don't need to run the expensive function on every single loop iteration, so I want to call it periodically:

for( int j = 0; j < Max; ++j ) {

    // ...

    if ( /* The condition I'm talking about */ ) 
        processQueuedEvents(); // Computationally expensive call

    // ...

}

At this point, I need to develop a proper condition for my periodic call. The condition should correlate to Max, I mean, if Max is larger, the expensive call is less-frequent and if Max is smaller the expensive call is more-frequent.

Does anybody have any suggestions or hints? For some reason, I have a hard time coming up with a proper condition.

1

There are 1 answers

0
NiVeR On BEST ANSWER

You didn't provide enough details about the increment function you want to use. If you are considering a liner one you can reason with factors of 10 in the following manner:

  • 0 <= Max < 10 - invoke the expensive call each execution of the loop.
  • 10 <= Max < 100 - invoke the expensive call each 10-th (j % 10 == 0) execution of the loop.
  • 100 <= Max < 1000 - invoke the expensive call each 100-th (j % 100 == 0) execution of the loop.

and so on.