Wednesday, February 28, 2007

Branch Prediction (cont.)

This code computes the minimum or maximum of two values without doing any branching. Because modern CPUs try and fetch instructions before they execute, and despite branch prediction code, branchless code still runs a bit faster.

int x; // we want to find the minimum of x and y
int y;
int r; // the result goes here
r = y + ((x - y) & -(x < y)); // min(x, y)
r = x - ((x - y) & -(x <>

1 comment:

Ravi said...

so pls repeat the code with the example of y=4 and x=3 and explain it to readers a little more