Computer Chess Club Archives


Search

Terms

Messages

Subject: Re: question about branchless code

Author: Dezhi Zhao

Date: 13:17:51 02/26/03

Go up one level in this thread


On February 26, 2003 at 15:41:26, Matt Taylor wrote:

>On February 26, 2003 at 14:04:16, Uri Blass wrote:
>
>>I had the following code in my program
>>
>>do
>>{
>>...
>>if (info[target]==EMPTA)
>>  target+=8;
>>else
>>  target=64;
>>}
>>while (target<64)
>>
>>I found that changing it to else break did not do my program faster.
>>
>>I think that with break I have branches and without break the compiler can
>>translate it to
>>
>>target=((info[target]==EMPTA)?target+8:64);
>>
>>My questions are
>>1)How can I write the code as branchless code without target=64 that is a waste
>>of time?
>>
>>2)I understood from previous discussion that for some reason ? is considered
>>branchless code.
>>What is the reason for it.
>>
>>It seems to me that using ? is the same as using if.
>>If it is not the case then what is the difference?
>>
>>Uri
>
>In this case, I don't think so. I'd need to look at assembly output to tell you.
>The bottom of the loop itself is a branch, so you're going to branch one way or
>another. If you use the break statement, you can make the loop more efficient by
>making the condition 1 (always true), and the compiler will change this into an
>unconditional branch. An unconditional branch never gets mispredicted. When the
>compiler sees your break statement, it will translate that into a jump out of
>the loop.
>
>Usually the ternary conditional construct can be converted into branchless code
>because usually the expressions are arithmetic, constants, and other branchless
>code. Also, they are small. The construct (condition ? 1 : 0) is particularly
>efficient since it translates into a single instruction.
>
>Branchless code isn't -always- more efficient, and any program more complex than
>"Hello world" requires at least some branches (for function calls and loops).
>Branchless code is preferred when each side of the branch only does a little bit
>of computation -- the branch itself may cost more than the computation it
>avoids.
>
>-Matt

You said it. I think if anyone wants to write optimal C or C++ code, he needs to
know assembly and CPU stuff.



This page took 0 seconds to execute

Last modified: Thu, 15 Apr 21 08:11:13 -0700

Current Computer Chess Club Forums at Talkchess. This site by Sean Mintz.