KatInterview

Bit-Level Speedups for a Hot Integer Loop

Math & Bit ManipulationModel answer
MediumModel answerMath & Bit Manipulationbit-manipulationbranchlesspopcount

Last 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:

  1. 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.
  2. Code. Short, concise snippets for each (C or Python is fine).
  3. Correctness. The identity behind each trick and the precondition that makes it valid (sign, power-of-two requirement, zero input, overflow).
  4. Hardware impact. How each change affects pipeline stalls, instruction-level parallelism, and cache and memory behavior.
  5. 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.