Nick
Nick

Reputation: 3451

Fast check number to be a multiple of the big number

I have a recursive algorithm that must be limited in time. If it takes too long, I am going to interrupt it. I check a time passed periodically as follows:

int g_counter = 0;
void myfunc()
{
    ++g_counter;
    if (g_counter % (1024 * 1024) == 0)
    {
        // measure time and interrupt if needed
    }
    ...
    myfunc(); // recursive call
    ...
}

Obviously, measurement slows down algorithm speed. Can this line:

if (g_counter % (1024 * 1024) == 0)

be optimized?

Update

I'm not stick to 1024*1024, any big number would be ok. I know that computer "likes" power-of-two-numbers. So maybe anyone can suggest something better that 1024*1024?

Upvotes: 1

Views: 200

Answers (2)

Peter
Peter

Reputation: 14947

int g_counter = 1024*1024;

...

if(--g_counter == 0) {
    g_counter = 1024*1024;
    // do your other checks
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726889

Since 1024*1024 is a power of two, you can do the same thing by ANDing with 1024*1024-1, like this:

if (g_counter & (1024 * 1024 - 1) == 0) {
    ...
}

Note that (1024 * 1024 - 1) is a constant expression, so it will be computed at compile time.

However, any decent optimizer will do the same thing for you, so there is no point in complicating things: changing your current code to the above should not make a difference.

Instead of optimizing this code, see if you could remove it altogether: run your algorithm in a separate thread, and set a timer that would wake up your main thread after a certain time interval has passed. This way you would not need to check the timer at all - the system will do it for you, letting your algorithm run only the "payload" code.

Upvotes: 1

Related Questions