Computer Chess Club Archives


Search

Terms

Messages

Subject: Re: Optimizing C code for speed

Author: Matt Taylor

Date: 10:29:54 01/01/03

Go up one level in this thread


On January 01, 2003 at 12:21:14, Vincent Diepeveen wrote:

>On January 01, 2003 at 11:50:58, Lieven Clarisse wrote:
>
>>I was wondering if there is a good book about how to write efficient C code. I
>>am not talking about algorithms, but the way *how* to write things, eg
>>
>>which is faster :
>>do {}  while()    or     while () {}
>
>compilers are very good in handling this but
>in general
>
>do {
>  ..
>} while();
>
>is better for processors (assuming no -O2 but -O) because it
>will allow fall through prediction of processors better.
>
>So the while() might get mispredicted when it is a fall through
>where the do .. while will usually get correctly predicted.
>
>Also while is an extra instruction. it is an extra JMP to above
>which the do .. while doesn't have.
>
>Another reason is you do 1 compare less in a do .. while versus
>a while .. do

Actually a do..while loop involves a backward jump (taken) whereas a while loop
involves a forward jump (not taken). It predicts the same. The extra jmp carries
at most 1 cycle penalty, and more than 50% of the time it will come for free.

>However compilers aren't stupid. usually they optimize it to the same
>thing.

They aren't the same thing. The compiler would be buggy if it did.

>Best regards,
>Vincent
>
>>-------
>>I know for instance that:
>>
>>ptr=&R[i];
>>if((*ptr==3)||(*ptr==7)) {;}
>>
>>is faster then:
>>
>>if((R[i]==3)||(R[i]==7)) {;}
>>
>>Is there a good book that reviews all those kinds of tricks?
>>
>>regards,
>>
>>Lieven



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.