Le 05/06/2011 03:05, Matt Turner a écrit :
> On Sat, Jun 4, 2011 at 7:14 PM, Benjamin Bellec <b.bel...@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.
diff --git a/src/gallium/auxiliary/util/u_math.h b/src/gallium/auxiliary/util/u_math.h
index 65a99fc..f37d9cc 100644
--- a/src/gallium/auxiliary/util/u_math.h
+++ b/src/gallium/auxiliary/util/u_math.h
@@ -493,17 +493,30 @@ util_logbase2(unsigned n)
 static INLINE unsigned
 util_next_power_of_two(unsigned x)
 {
-   unsigned i;
+#if defined(PIPE_CC_GCC)
+   if (x == 0)
+       return 1;
+   else
+       return (1 << (32 - __builtin_clz(x - 1)));
+#else
+   unsigned val = x;
 
    if (x == 0)
       return 1;
 
-   --x;
-
-   for (i = 1; i < sizeof(unsigned) * 8; i <<= 1)
-      x |= x >> i;
-
-   return x + 1;
+   /* check if x is already a power of two */
+   if ((x & (x - 1)) == 0)
+      return x;
+
+   val--;
+   val = (val >> 1) | val;
+   val = (val >> 2) | val;
+   val = (val >> 4) | val;
+   val = (val >> 8) | val;
+   val = (val >> 16) | val;
+   val++;
+   return val;
+#endif
 }
 
 
_______________________________________________
mesa-dev mailing list
mesa-dev@lists.freedesktop.org
http://lists.freedesktop.org/mailman/listinfo/mesa-dev

Reply via email to