tofo
tofo

Reputation: 388

Efficient way to fetch amount from signed integer until zero in C++?

What is an efficient way in C++ to decrement and return a limited portion of an signed long integer until zero. The portion size is defined in an unsigned integer?

The use is in a busy interrupt routine of a small 16MHz processor.

I was experimenting with something like this:

#define limit(amt,lim) ((amt)<(-lim)?(-lim):((amt)>(lim)?(lim):(amt)))

long pile = 3452;
int maxportion = 100;


while (pile!=0)
{

    int portion;
    portion = limit(pile, maxportion);
    pile -= portion;

    //Code to apply portion here..

}

The while loop is just for demonstration. For the implementation i hope to find a "subtract and return portion" that feels ok to execute once every interrupt regardless of pile is zero or not.

Upvotes: 1

Views: 101

Answers (1)

Ami Tavory
Ami Tavory

Reputation: 76366

As @M.M writes, you might consider changing the macro to an inline function. The only thing I might add is that, if you know the distribution of cases, you might speed up things using something like likely and unlikely. For example, here is code optimized for the case where |amt| < |lim|.

inline long limit(long amt,long lim)
{
    if(unlikely(amt < -lim))
        return -lim;
    else 
    {   
        if(unlikely(amt > lim))
            return lim;
        return amt;
      }
}

As usual with performance, YMMV. You should profile and see.

Upvotes: 2

Related Questions