What is the most efficient way of rounding a usize up to a nearest multiple of 8? What I have so far is:

`((x + 7) / 8) * 8`

What is the most efficient way of rounding a usize up to a nearest multiple of 8? What I have so far is:

`((x + 7) / 8) * 8`

0 Likes

Of course both your approach and mine are susceptible to overflow when `x`

is just slightly less than `usize::MAX`

. I presumed that you didn’t care about that condition, since you didn’t address it in your code.

0 Likes

Incidentally, your measure of “efficiency”, in number of operators, is not what I inferred. I thought that you meant CPU efficiency. Logical And is almost certainly more efficient (in both time and energy) than Divide followed by Multiply. It is also less likely to leak information through a timing side-channel.

0 Likes

What you have is fine, @zeroexcuses; the compiler will turn it into what @TomP said.

This is the kind of simple, local transformation that LLVM is extraordinary good at. Write the clear thing; let LLVM optimize the exact instructions.

0 Likes