Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What techniques to avoid conditional branching do you know?

Sometimes a loop where the CPU spends most of the time has some branch prediction miss (misprediction) very often (near .5 probability.) I've seen a few techniques on very isolated threads but never a list. The ones I know already fix situations where the condition can be turned to a bool and that 0/1 is used in some way to change. Are there other conditional branches that can be avoided?

e.g. (pseudocode)

loop () {   if (in[i] < C )     out[o++] = in[i++]   ... } 

Can be rewritten, arguably losing some readability, with something like this:

loop() {   out[o] = in[i]  // copy anyway, just don't increment   inc = in[i] < C  // increment counters? (0 or 1)   o += inc   i += inc } 

Also I've seen techniques in the wild changing && to & in the conditional in certain contexts escaping my mind right now. I'm a rookie at this level of optimization but it sure feels like there's got to be more.

like image 633
alecco Avatar asked Oct 24 '09 23:10

alecco


People also ask

What is the conditional branching?

A conditional branch instruction is a branch instruction that may or may not generate a transmission of control that relies upon the value of stored bits in the PSR (processor status register). It provides decision-making capabilities in the control unit.

What is a conditional branching control structure?

�Conditional branching. Conditional branching is the term used to describe the set of operations such as 'if <condition> do <something> else do <something else>' and the various case and switch statements in conventional imperative languages such as C, PERL and Java.

What are conditional branching statements in python?

Branching statements in Python are used to change the normal flow of execution based on some condition. Python provides three branching statements break, continue and return. In Python pass also a branching statement, but it is a null statement. The return branching statement is used to explicitly return from a method.


1 Answers

Using Matt Joiner's example:

if (b > a) b = a; 

You could also do the following, without having to dig into assembly code:

bool if_else = b > a; b = a * if_else + b * !if_else; 
like image 55
Mads Rønnow Avatar answered Sep 20 '22 19:09

Mads Rønnow