Execution time bottleneck: How to speed up execution?

George V. Reilly gvr at cs.brown.edu
Wed Feb 13 16:41:32 AEST 1991


In article <1991Feb12.233522.5195 at Think.COM>, barmar at think.com
(Barry Margolin) writes an excellent followup to Jeff Racine's
question about hand-optimizing a bottleneck in his code.

> Execution time query:
>
> I have the following nested loop in which I must sum (over all i), for each
> x[j], e raised to the power x[i]-x[j] squared (times a constant).
>
> This section of the program is of order n-squared (i.e. execution time
> increases at the rate of the number of observations squared).
>
>    for (j=1; j <= n; j++) {
>       sum = 0.0;
>       for (i=1; i<= n; i++) {
>          sum += exp( con * (x[i]-x[j]) * (x[i]-x[j]) );
>       }
>       a[j] = k*sum;
>    }
>

I second Barry's recommendation of Bentley's `Writing Efficient Programs'.

One additional suggestion: if you can make assertions about
	r = con * (x[i] - x[j]) * (x[i] - x[j])
such as r is an integer in the range 1 <= r <= 50 or 
r is a multiple of 0.125 in the range -3.75 <= r <= +7.875,
then you can precompute a table of all of the possible results.
Caveat: if r is a multiple of some number (e.g., 0.1) which
cannot be expressed as an exact binary fraction (assuming
binary FP hardware), then the results may be inaccurate.

In article <15884.27b919a3 at levels.sait.edu.au> marwk at levels.sait.edu.au (Ray)
writes:

> (1) rewrite the sum as Sum = 2 * S{i=1,i=n-1} S{j=i+1,j=n} f(i,j)
>     this cuts the number of calculations in half.

I can make no sense of this statement.  It's not equivalent to
the original code.
________________
George V. Reilly   `| Pas une pipe'	gvr at cs.brown.edu   +1 (401) 863-7684
uunet!brunix!gvr   gvr at browncs.bitnet	Box 1910, Brown U, Prov, RI 02912



More information about the Comp.lang.c mailing list