It's me again, with a new minor optimization for the
util_next_power_of_two() function.

This patch implements a faster algorithm, still taken from Wikipedia (
http://en.wikipedia.org/wiki/Power_of_two#Algorithm_to_round_up_to_power_of_two
).
But especially, I added the most common values used by this function. I
noted that ETQW, TA Spring and ExtremeTuxRacer call often "good" values.
I can think that most OpenGL apps uses also these values.

I have benchmarked this. With -O2 optimization, this new function is
twice faster than the former. Without GCC optimization the difference is
even bigger.

There is no piglit regressions.

But there is an issue, during compilation there is an error (-Wall)
"warning: right shift count >= width of type [enabled by default]".

Regards.

Benjamin Bellec
diff --git a/src/gallium/auxiliary/util/u_math.h b/src/gallium/auxiliary/util/u_math.h
index 65a99fc..7d260ae 100644
--- a/src/gallium/auxiliary/util/u_math.h
+++ b/src/gallium/auxiliary/util/u_math.h
@@ -486,24 +486,44 @@ util_logbase2(unsigned n)
    return pos;
 }
 
-
 /**
  * Returns the smallest power of two >= x
  */
 static INLINE unsigned
 util_next_power_of_two(unsigned x)
 {
-   unsigned i;
-
-   if (x == 0)
-      return 1;
-
-   --x;
-
-   for (i = 1; i < sizeof(unsigned) * 8; i <<= 1)
-      x |= x >> i;
-
-   return x + 1;
+   unsigned val = x;
+
+   switch (x)
+   {
+      case 1:
+      case 2:
+      case 4:
+      case 8:
+      case 16:
+      case 32:
+      case 64:
+      case 128:
+      case 256:
+      case 512:
+      case 1024:
+      case 2048:
+      case 4096:
+         return x; /* this is the most commonly used values */
+      case 0:
+         return 1;
+      default:
+         val--;
+         val = (val >> 1) | val;
+         val = (val >> 2) | val;
+         val = (val >> 4) | val;
+         val = (val >> 8) | val;
+         val = (val >> 16) | val;
+         if (sizeof(unsigned) == 8)
+            val = (val >> 32) | val;
+         val++;
+         return val;
+   }
 }
 
 
_______________________________________________
mesa-dev mailing list
mesa-dev@lists.freedesktop.org
http://lists.freedesktop.org/mailman/listinfo/mesa-dev

Reply via email to