1

I'm performing this operation a lot, and I want to avoid branch-prediction problems, so I'm asking here.

For signed integer values, using only integer or bitwise arithmetic, can I implement the following statement without an IF clause, or other control clauses? A preferable solution would be word-length independent.

if value < 0 {
    value = 0
}
tuskiomi
  • 190
  • 1
  • 15
  • 2
    The first thing to check is that that code really does compile down to a branch. It could compile to a conditional load. If it is a branch could try v *= (v>=0); or v &= -(v>=0); Whether these are actually faster of course could only be determined by measurement. – dmuir Feb 22 '21 at 17:11
  • 2
    Not sure which language you're using, but if there's a built in "max" function you might get better performance than your `if`, e.g. `value = max(0, value)`. This may already have some optimization, or if you're using a compiled language, the compiler may have some hints at an optimization. Your friend in this case is to code up a number of approaches (including the nice one dmuir provides above) and profile them. Before you do any of that though, you should verifiy this is a bottleneck in your program. You may be prematurely optimizing. – andand Feb 22 '21 at 18:15
  • @andand if I do that, I'll write an answer.. – tuskiomi Feb 22 '21 at 18:23
  • If you have an arithmetic right shift in the language you're using, `value &= ~(value >> (sizeof(value)*CHAR_BIT)-1) )` could work. i.e. right shift to broadcast the sign bit, then ANDNOT. Might be faster than booleanizing a compare result, especially on x86 with [BMI1 for `andn`](https://www.felixcloutier.com/x86/andn). – Peter Cordes Feb 23 '21 at 03:54

0 Answers0