branchless code..

Posted on March 3, 2007. Filed under: computer science, programming |

Branchless code, is much more efficient than otherwise, even on modern processors, despite branch prediction logic, simply because they still try and fetch instructions before they execute. that said, below is a branchless code to compute maximum and minimum of two nos.

int x; int y; /*the two nos*/
int r; /* the result goes here */
r = y + ((x - y) & -(x < y)); /* min(x, y) */
r = x - ((x - y) & -(x < y)); /* max(x, y) 
*/

ALU full throttle!

Make a Comment

Make a Comment: ( 4 so far )

blockquote and a tags work here.

4 Responses to “branchless code..”

RSS Feed for Nirmal Thacker Comments RSS Feed

but you cant alwayz convert a branch(ed) code to a branchless one can you?

but you cant alwayz convert a branch(ed) code to a branchless one can you? hey and this theme of yours..isnt rlly showing up well on my IE6..:s

@zaki- yes of course, converting a branched code to branchless may not always be possible. true that.
thanks for the theme feedback…since i’ve not used any kind of CSS here, all i can do is buzz the guys at wordpress. it looks messy in IE 7 as well. I never realized this, since im better off with firefox

This is not branchless code. The expression (x>8*sizeof(int)-1 in place of -(x<y). In principle the compiler could do this for you but I know of no compiler that does.

One very nice application of this kind of branchless logic is to make a branchless binary search. If the number of iterations is constant you can even unroll the loop into a tiny fragment that still fits happily in L1 cache.


Where's The Comment Form?

  •  

    March 2007
    M T W T F S S
    « Feb   Apr »
     1234
    567891011
    12131415161718
    19202122232425
    262728293031  
  • a

  • Archives

  • Blog Stats

    • 52,530 hits
  •       

    This work is licensed under a Creative Commons Attribution-No Derivative Works 3.0 Unported

    Beware however that this refers only to parts which are obviously written by me and do not have any other information about licencing. Quoted text, pictures and other content created by others is copyrighted by the corresponding authors. If you are in doubt, ask before republishing any content.

Liked it here?
Why not try sites on the blogroll...