[Mesa-dev] [PATCH] faster util_next_power_of_two() function

Matt Turner mattst88 at gmail.com
Mon Jun 6 08:53:21 PDT 2011


On Mon, Jun 6, 2011 at 11:34 AM, Roland Scheidegger <sroland at vmware.com> wrote:
> Am 05.06.2011 03:55, schrieb Benjamin Bellec:
>> Le 05/06/2011 03:05, Matt Turner a écrit :
>>> On Sat, Jun 4, 2011 at 7:14 PM, Benjamin Bellec <b.bellec at gmail.com> wrote:
>>>> Le 03/06/2011 06:09, Matt Turner a écrit :
>>>>> Also, if you want to check if the value is already a power-of-two,
>>>>> instead of a case statement for every POT (including 0), just do the
>>>>> standard is-power-of-two check:
>>>>>
>>>>> (x & (x - 1)) == 0
>>>>
>>>> My own tests (on a Core2) shows that it's less efficient to do that, at
>>>> least with -O2 optimization enabled. With -O0, it's equal.
>>>
>>> For what input set? Powers of two?
>> Both, my test case loops with 29 POT and 6 NPOT.
>> I'm doing this because the OpenGL games that I have tested call the
>> function more often with "good" values.
>>
>>>
>>> Doesn't really matter, since the function isn't a hot path or
>>> anything, but I'd suppose that the Linux kernel has its
>>> is_power_of_2() function for a reason--that it's pretty ugly to have
>>> lots of case statements like powers of two.
>>>
>>> Matt
>> Ok, so here is a v3 patch which replace the switch statement.
>
> I like this one better too.
> Do we actually need the x == 0 special case or would it be ok if we just
> remove that (which will return 0)?
>
> Roland

It depends on the behavior you want. (x & (x - 1)) recognizes 0 as a
power of two, so it would just return zero. I don't really know under
what circumstances 0 would be input to this function.

FYI, the function in the kernel has a special case that causes it to
not detect 0 as a power of two.

Matt


More information about the mesa-dev mailing list