Quote:
> I need to highly optimise a large piece of code and maintain ANSI
> compatibility.
Be warned that what you are trying to do may not be
easy, and may not be posssible. On the other hand [1]
you may be able to get considerable speed increase
with very little work.
Also be warned that speed and ANSI compatibility
may turn out to be trade offs.
Often you may have to do things like
#ifdef NT_INTEL
......
#elif
....
#elif SOLARIS_SPARC
....
#elif LINUX_INTEL
....
#elif LINUX_SPARC
......
#else
<you already have something that works, it may not be fast but it
works>
#endif
Ugly, but it can be effective.
First
PROFILE
Even if you do not have profiling tools, a few
well placed printf's (followed by fflush's) can
often pinpoint where a program spends its time.
It is very important to profile, because quite often
a program will spend most of its time in only
a small percentage of the code (and where
a program spends its time is often very
surprising). If you don't profile, you can
waste a lot of time speeding up code
that has no practical impact on the run time.
Make sure you have an optimizing compiler.
Make sure you are using the riight level of optimization
(Try using a different compiler (get gcc for your platform,
it can be faster than comercial compilers) )
If you can, set up a tool so you can watch the CPU
usage while your program runs. This can be
a great help in determining whether the program
is held up by the CPU (CPU bound) or
held up by something else, usually
I/O (i/o bound).
See up a test run. Whenever you try
something, test to make sure you
still get the same answer, and to
see if it actually helps.
Quote:
> I know that I can use 'inline' on small functions,
Wel, if you want to be ansi (C89) compatible, then
you can't use inline. Even if you have a compiler
that recognizes inline, there may be no
guaratees that adding "inline" will do anything.
What you can do is wirte macros in
place of functions, in effect forcing
inlining. Don't bother unless your
profile indicates that the function is called a lot,
by functions that use appreciable time.
Quote:
> and use the '?' to
> replace certain 'if' blocks.
Unless you have a brain-dead compiler,
this will make no difference at all
(except perhaps making the code
harder to read). If you do have a brain-
dead compiler, you should be working on
replacing the compiler, not tweaking
the code.
Quote:
> What other general things can I do? (I know
> it's hard to answer without seeing the code).
I will second the advice to look at
http://www.ontek.com/mikey/optimization.html
-William Hughes
[1] Go not to the elves for advice, for they will say
both no and yes.