Bottom and top bit indices are related: value & -value gives you the number where the only set bit is the bottom (least significant) one, then you can use clz.
Up to now, i've been using a LIFO list or table in order to track slot allocation. Obviously, since the table costs one pointer per slot, each slot has to be "reasonably sized" for this strategy to be effective.
September 10, 2012 at 4:52 AM
You want to be able to allocate slots, free slots, and iterate on the allocated slot
indexes. In particular :
int AllocateSlot( allocator );
void FreeSlot( allocator , int slot );
int GetNextSlot( iterator );
Say you can limit the maximum number of allocations to 32 or 64, then obviously you should use bit operations.
But you also want to avoid variable shifts. What do you do ?
Something like this :
slot);
}
int __forceinline GetNextSlot( U32 & set )
{
ASSERT( set != 0 );
int slot = BottomBitIndex(set);
// turn off bottom bit :
set = set & (set-1);
return slot;
}
/*
// example iteration :
U32 cur = set;
while(cur)
{
int i = GetNextSlot(cur);
lprintfvar(i);
}
*/
However, this uses the bottom bit index, which is not as portably fast as using the top bit index (aka count leading zeros).
(there are some platforms/gcc versions where builtin_ctz does not exist at all, and others where it exists but is not fast because there's
no direct instruction set correspondence).
So, the straightforward version that uses shifts and clz is probably better in practice.
ADDENDUM : Duh, version of same using only TopBitIndex and no variable shifts :
slot) );
return slot;
}
(note the forceinline is important because the use of actual references is catastrophic on many platforms
(due to LHS), we need these to get compiled like macros).
"06-14-11 - A simple allocator"
3 Comments -
Bottom and top bit indices are related: value & -value gives you the number where the only set bit is the bottom (least significant) one, then you can use clz.
June 15, 2011 at 10:14 AM
Yeah, of course. Amended.
June 15, 2011 at 10:38 AM
Up to now, i've been using a LIFO list or table in order to track slot allocation.
Obviously, since the table costs one pointer per slot, each slot has to be "reasonably sized" for this strategy to be effective.
September 10, 2012 at 4:52 AM