Skip to contentSkip to conversation

lib/find_bit.c: micro-optimise find_next_*_bit

PATCH New [email protected] 1 participant 1 message Feb 24, 2017

Subsystems (2)
lore
Share & tools
lore

[email protected]

author maintainer
#0 lore raw

PATCH 109/124 lib/find_bit.c: micro-optimise find_next_*_bit

From: Matthew Wilcox <[email protected]>
Subject: lib/find_bit.c: micro-optimise find_next_*_bit

This saves 32 bytes on my x86-64 build, mostly due to alignment considerations and sharing more code between find_next_bit and find_next_zero_bit, but it does save a couple of instructions.

There's really two parts to this commit. First, the first half of the
test: (!nbits || start >= nbits) is trivially a subset of the second half, since nbits and start are both unsigned. Second, while looking at the disassembly, I noticed that GCC was predicting the branch taken. Since this is a failure case, it's clearly the less likely of the two branches, so add an unlikely() to override GCC's heuristics.

---

 lib/find_bit.c       |    4 ++--
 tools/lib/find_bit.c |    2 +-
 2 files changed, 3 insertions(+), 3 deletions(-)
lib/find_bit.c renamed from lib/find_bit.c~find_bit-micro-optimise-find_next__bit +2 -2
diff -puN lib/find_bit.c~find_bit-micro-optimise-find_next__bit lib/find_bit.c
@@ -33,7 +33,7 @@ static unsigned long _find_next_bit(cons
 {
 	unsigned long tmp;
 
-	if (!nbits || start >= nbits)
+	if (unlikely(start >= nbits))
 		return nbits;
 
 	tmp = addr[start / BITS_PER_LONG] ^ invert;
@@ -151,7 +151,7 @@ static unsigned long _find_next_bit_le(c
 {
 	unsigned long tmp;
 
-	if (!nbits || start >= nbits)
+	if (unlikely(start >= nbits))
 		return nbits;
 
 	tmp = addr[start / BITS_PER_LONG] ^ invert;
tools/lib/find_bit.c renamed from tools/lib/find_bit.c~find_bit-micro-optimise-find_next__bit +1 -1
diff -puN tools/lib/find_bit.c~find_bit-micro-optimise-find_next__bit tools/lib/find_bit.c
@@ -34,7 +34,7 @@ static unsigned long _find_next_bit(cons
 {
 	unsigned long tmp;
 
-	if (!nbits || start >= nbits)
+	if (unlikely(start >= nbits))
 		return nbits;
 
 	tmp = addr[start / BITS_PER_LONG] ^ invert;

_