Permalink
Browse files

lib: optimize nearest_power

Instead of looping over each bit of a size_t, we can use a closed form
expression.
  • Loading branch information...
jeffpc authored and cmouse committed Aug 30, 2017
1 parent 9dadffc commit 0dac2f5f0a0f25d8f6b789ba089f1a2d01c529a6
Showing with 15 additions and 4 deletions.
  1. +14 −4 src/lib/bits.c
  2. +1 −0 src/lib/bits.h
View
@@ -2,14 +2,24 @@
#include "lib.h"
/*
* We could use bits_required64() unconditionally, but that's unnecessary
* and way more heavy weight on 32-bit systems.
*/
#ifdef _LP64
#define BITS_REQUIRED(x) bits_required64(x)
#else
#define BITS_REQUIRED(x) bits_required32(x)
#endif
size_t nearest_power(size_t num)
{
size_t n = 1;
i_assert(num <= ((size_t)1 << (CHAR_BIT*sizeof(size_t) - 1)));
while (n < num) n <<= 1;
return n;
if (num == 0)
return 1;
return 1UL << BITS_REQUIRED(num - 1);
}
#if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
View
@@ -6,6 +6,7 @@
#define BIT(n) (1u << (n))
/* Returns x, such that x is the smallest power of 2 >= num. */
size_t nearest_power(size_t num) ATTR_CONST;
/* Returns TRUE if 2^x=num, i.e. if num has only a single bit set to 1. */

0 comments on commit 0dac2f5

Please sign in to comment.