Bit-Level Speedups for a Hot Integer Loop
Math & Bit ManipulationModel answerLast updated
Choose bit-twiddling techniques that cut branch mispredictions and memory traffic in a tight integer loop, justify their correctness, and reason about their CPU and cache effects.
You own a tight inner loop that does a lot of integer work: it advances a ring-buffer index, compares large sets of boolean flags, clamps values into a range, and loads from buffers that may or may not be aligned. Profiling shows time lost to integer division, mispredicted branches, and cache misses.
Describe how you would use bit-level techniques to speed it up. Your answer should cover:
- Techniques. At minimum: population count, modulo by a power of two via masking, branchless conditional updates using bitwise selects, and alignment checks or round-up.
- Code. Short, concise snippets for each (C or Python is fine).
- Correctness. The identity behind each trick and the precondition that makes it valid (sign, power-of-two requirement, zero input, overflow).
- Hardware impact. How each change affects pipeline stalls, instruction-level parallelism, and cache and memory behavior.
- Judgment. When a trick will not help or will make things worse, and how you would verify a gain.
Hints
Hint 1
Start from what each trick replaces: a divide, a data-dependent branch, a per-bit loop, or a byte-per-flag array. For each one, write down the identity and the condition under which it holds.
Hint 2
For modulo by a mask, check negative inputs and the requirement that the modulus is a power of two. For power-of-two tests and lowest-set-bit tricks, check what happens at x = 0 and in two's complement.
Hint 3
A branchless version turns a control dependency into a data dependency. Think about when a branch is well predicted versus random, and what you would measure (for example, branch-miss counters) before rewriting.
Hint 4
For memory, consider the size of a bitset versus a byte array, cache-line and page-boundary straddling, and how power-of-two strides can cause conflict misses.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The goal is to replace expensive or unpredictable operations with cheap ALU operations, while being explicit about each trick's precondition and about when it does not pay off. I would organize the answer as: identity, correctness, hardware effect, and then measurement.
Techniques and why they are correct
| Problem | Trick | Precondition |
|---|---|---|
| Division in ring index or hashing | x % m becomes x & (m-1) | m is a power of two; x unsigned or floor semantics wanted |
Is x a power of two? | x != 0 && (x & (x-1)) == 0 | Guard against x == 0 |
| Count shared flags | popcount(a & b) per 64-bit word | Flags packed as bits |
| Visit each set bit | low = x & -x; idx = ctz(x); x &= x-1 | x != 0 before ctz |
| Conditional update | r = b ^ ((a ^ b) & -(cond)) | cond is 0 or 1 |
| Clamp, min, max | Same select with cond = (v < lo) | Watch signed overflow |
| Alignment test | (p & (A-1)) == 0 | A is a power of two |
| Round up to alignment | (p + A - 1) & ~(A - 1) | A is a power of two; no overflow |
// ring index without division (CAP is a power of two)
idx = (idx + 1) & (CAP - 1);
// count matching flags, 64 per load
for (size_t w = 0; w < nwords; w++)
hits += __builtin_popcountll(a[w] & b[w]);
// iterate set bits
while (x) {
int i = __builtin_ctzll(x);
handle(i);
x &= x - 1;
}
// branchless select and clamp
int64_t m = -(int64_t)(v < lo);
v = v ^ ((v ^ lo) & m);
// alignment
bool ok = ((uintptr_t)p & 31) == 0;
size_t up = (n + 63) & ~(size_t)63;
def is_pow2(x): return x > 0 and (x & (x - 1)) == 0
def mod_pow2(x, m):
assert is_pow2(m); return x & (m - 1)
def select(cond, a, b):
mask = -int(cond); return b ^ ((a ^ b) & mask)
def align_up(addr, a):
assert is_pow2(a); return (addr + a - 1) & ~(a - 1)
Python ints are arbitrary precision, so this shows semantics rather than speed.
Why the identities hold
- Mask modulo. For
m = 2^k, the remainder is exactly the lowkbits, andm-1is the mask of those bits. In C,-5 % 8is-5(truncation) while-5 & 7is3(floor). Use unsigned types or accept floor semantics deliberately. - Power-of-two test.
x-1flips the lowest set bit and all bits below it, so the AND is zero exactly when one bit is set.0 & -1is also zero, hence thex != 0guard. - Lowest set bit.
-x = ~x + 1flips everything above the lowest set bit and preserves that bit, sox & -xisolates it.x & (x-1)clears it, giving O(popcount) iteration instead of O(width). - Select. With
maskall ones the result isb ^ a ^ b = a; withmaskzero the result isb. - Align up. Adding
A-1carries into the next multiple unlesspis already aligned, and masking truncates the low bits.
Hardware impact
Branches and pipeline stalls. A mispredicted branch costs roughly 15 to 20 cycles of flushed work. For data-dependent, unpredictable conditions, branchless selects (compiled to cmov or SIMD blends) remove that cost. For well-predicted branches, branchless code can be slower, because it converts a control dependency the CPU speculates past into a data dependency it must wait on, lengthening the critical path. Check branch-misses with perf stat before rewriting.
ILP. AND, XOR, shifts, and POPCNT are 1 to 3 cycle operations that can issue on multiple ports. Integer div has tens of cycles of latency and limited pipelining, so removing it frees the scheduler. To keep ILP high, avoid one long accumulation chain: use 2 to 4 independent popcount accumulators and combine at the end. Branch-free bodies also auto-vectorize (blends, min/max), processing 4 to 8 lanes per instruction.
Cache and memory.
- A bitset is 8x smaller than a
bool[]and 32x smaller than anint[]. One 64-byte line holds 512 flags, so more of the working set stays in L1/L2, and set operations become bandwidth-friendly word-wide ops. - Loads that straddle a cache line touch two lines; straddling a 4 KiB page may cost two TLB lookups. Aligned buffers allow aligned SIMD loads, and padding or rounding to 64 bytes avoids false sharing between threads.
- Large power-of-two strides can map to the same cache sets and cause conflict misses. Pad rows by one cache line to fix it.
Complexity
Each primitive is O(1) time and space on fixed-width words. Iterating set bits is O(popcount). Intersection-count over n flags is O(n/64) word operations versus O(n) for a byte array.
Edge cases and common mistakes
- Mask modulo with a non-power-of-two modulus silently gives wrong answers. Assert once outside the loop.
is_pow2(0)must be false.__builtin_ctz(0)is undefined. Guard against zero.absandmintricks overflow atINT64_MIN.- Right-shifting negative signed values is implementation-defined before C++20/C23. Prefer unsigned types or intrinsics.
- Hand-writing branchless code the compiler would already emit as
cmov, hurting readability for no gain. - Applying tricks without measuring. A good answer states a benchmark plan: representative data,
perf statfor mispredicts and cache misses, and comparison of the compiler's output at-O2/-O3.
Summary
Use masks instead of division when the modulus is a power of two, popcount and bitsets for flag-set work, lowest-bit iteration for sparse sets, selects for unpredictable conditionals, and alignment arithmetic for memory layout. State each precondition, explain the effect on branches, ILP, and cache, and confirm the win with measurements.