[comp.lang.c++] Efficiency of complex arithmetic in C++

dhale@csm9a.UUCP (Dave Hale) (08/01/90)

I am using AT&T C++ Release 2.1 for complex arithmetic, but
I find the resulting code to be much slower than that from doing
complex arithmetic in plain C, the hard way.  A simple example
is the code below, which fills an array of complex objects.
The C++ way is much (more than 3 times) slower than the
plain C way.  I first observed this slowdown with more
complicated, arithmetic expressions involving complex, but
then tried progessively simpler expressions until I obtained
the example provided below.

The output (not shown below) of cfront indicates that the 
complex(float,float) constructor uses a temporary struct complex 
variable, instead of building the complex directly in the 
left-hand-side of the expression.

Any suggestions on how to avoid such temporaries or, in general,
on how to make complex arithmetic in AT&T C++ more efficient?

-------------------------- cut here ------------------------------
// a very simple complex
class complex
{
public:
	float r,i; // should be private, but may have to get dirty
	inline complex() {}
	inline complex(float re, float im=0.0) {r=re; i=im;}
};

// a non-member function that works with complex variables
void func(int n, float a, float b, complex *c)
{
	for (int i=0; i<n; ++i) {
	
		// clean, but slow
		c[i] = complex(a,b);
		
		// dirty, but fast
		//c[i].r = a;  c[i].i = b;
	}
}

// exercise the function
#define NLOOP 1000
#define N 10000
main()
{
	int n=N,nloop=NLOOP;
	float a=1.0,b=2.0;
	complex *c = new complex[n];
	for (int iloop=0; iloop<nloop; ++iloop)
		func(n,a,b,c);
}
-- 
Dave Hale    dhale@csm9a.mines.colorado.edu    (303) 273-3408
Department of Geophysics, Colorado School of Mines, Golden, CO   80401

chris@ctk1.UUCP (Chris Old) (08/14/90)

In article <2223@csm9a.UUCP> dhale@csm9a.UUCP (Dave Hale) writes:

>I am using AT&T C++ Release 2.1 for complex arithmetic, but
>I find the resulting code to be much slower than that from doing
>complex arithmetic in plain C, the hard way.

>Any suggestions on how to avoid such temporaries or, in general,
>on how to make complex arithmetic in AT&T C++ more efficient?

A temporary solution (until the gurus sort out the real problem) is to
do the complex arithmetic in plain C++, the hard way.

--------------------
Chris Old  (C.t.K.)               : chris@ctk1.UUCP
Tran Systems Ltd                  : ddsw1!olsa99!ctk1!chris