Computer Chess Club Archives


Search

Terms

Messages

Subject: Re: Optimizing C code for speed

Author: Matt Taylor

Date: 19:15:27 01/01/03

Go up one level in this thread


On January 01, 2003 at 19:28:01, Uri Blass wrote:

>On January 01, 2003 at 19:02:03, Bruce Moreland 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 () {}
>>>
>>>-------
>>>I know for instance that:
>>>
>>>ptr=&R[i];
>>>if((*ptr==3)||(*ptr==7)) {;}
>>>
>>>is faster then:
>>>
>>>if((R[i]==3)||(R[i]==7)) {;}
>>
>>How do you know this?
>>
>>It is true or not true, depending upon the local context.  If you are using "R"
>>and "i" together, the compiler can figure out what you are doing sometimes.  If
>>this is one of those times, then doing weird pointer stuff is just confusing to
>>everyone -- possibly including the compiler.
>>
>>Also, why do you care if your code goes fast?  This seems like a stupid
>>question, but often, it is the *best* question, and the answer is, "I don't".
>>
>>And even if you find something that needs to go fast, the fact that you ask the
>>question, and need to know the real answer, means that you need to go to the
>>root, which is in this case the generated assembly and profiler output.
>>
>>bruce
>
>I agree.
>
>I think that in cases that you care about speed then it is more important to
>care first about speed of the logic and not about speed of C.
>
>It means that if you have a condition A&&B and it is usually wrong because of B
>then it may be better to change it to B&&A.

On that note you can think in higher terms of algorithms themselves. If you have
a slow algorithm, think about ways to improve upon the algorithm. Assembly-level
optimizations (and ways to encourage them) should be a last resort. They won't
get you nearly as far as better algorithms will.

>It is something that the compiler cannot do by itself because the compiler is
>not going to take the risk that B can cause a crash when A is false and the
>compiler has no way to know that B cannot cause a crash.

Depends. If A or B rely on a function call, yes. If they're based exclusively on
data and don't modify anything, the compiler can swap them. (However, it won't
unless you profile.)

-Matt



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.