dumping ground for random patches and texts
 help / color / mirror / Atom feed
* [PATCH] reduce branches for size class calculation
@ 2024-04-05 21:40 Eric Wong
  0 siblings, 0 replies; only message in thread
From: Eric Wong @ 2024-04-05 21:40 UTC (permalink / raw)
  To: spew

We can use bit twiddling to find the next power-of-two without
branching for each iteration of the loop (since the new loop
is simple enough for a compiler to unroll).
---
 mwrap_core.h | 16 ++++++----------
 1 file changed, 6 insertions(+), 10 deletions(-)

diff --git a/mwrap_core.h b/mwrap_core.h
index 6467f1c..02b42ad 100644
--- a/mwrap_core.h
+++ b/mwrap_core.h
@@ -686,17 +686,13 @@ static inline size_t size_class_pad(size_t bytes)
 	 * minimize fragmentation.  This means we pay a 0-20% overhead on
 	 * the initial allocations to improve the likelyhood of reuse.
 	 */
-	size_t max = sizeof(void *) << 5;
-	size_t nxt;
-	do {
-		if (bytes <= max) {
-			size_t sc_bytes = size_align(bytes, max >> 3);
-			return sc_bytes <= mm_thresh ? sc_bytes : bytes;
-		}
-		nxt = max << 1;
-	} while (nxt > max && nxt < mm_thresh && (max = nxt));
+	size_t np2 = bytes - 1;
+	for (size_t i = 1; i < sizeof(size_t) * CHAR_BIT; i <<= 1)
+		np2 |= np2 >> i;
+	++np2; // next power-of-two
 
-	return bytes;
+	size_t sc_bytes = size_align(bytes, np2 >> 3);
+	return sc_bytes < mm_thresh ? sc_bytes : mm_thresh;
 }
 
 void *malloc(size_t size)

^ permalink raw reply related	[flat|nested] only message in thread

only message in thread, other threads:[~2024-04-05 21:40 UTC | newest]

Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2024-04-05 21:40 [PATCH] reduce branches for size class calculation Eric Wong

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).