Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this reinterpret_cast OK to do

I am a EE, not a code expert, so please bear with me here.

I am using Embarcadero C++ Builder (XE3).

I have an FFT algorithm which does a fair number of operations on complex numbers. I found out that if I bypass Embarcadero's complex math library, and do all the calculations in my own code, my FFT will run about 4.5 times faster. The 4 operations shown here all require an inordinate amount of time.

#include <dinkumware\complex>
#define ComplexD std::complex<double>
ComplexD X, Y, Z, FFTInput[1024];
double x, y;
Z = X * Y; 
x = X.real();
y = X.imag();
Z = ComplexD(x,y); 

Replacing the multiplication with my own cross multiply cut my execution times in half. My concern however is with the way I am accessing the real and imaginary parts of the input array. I am doing this:

double *Input;
Input = reinterpret_cast<double *>(FFTInput);
// Then these statements are equivalent.
x = FFTInput[n].real();
y = FFTInput[n].imag();
x = Input[2*n];
y = Input[2*n+1];

Doing this cut my execution times in half again, but I don't know if this reinterpret_cast is a wise thing to do. I could change the input array to two doubles instead of a complex, but I am using this FFT in numerous programs and don't want to rewrite everything.

Is this reinterpret_cast OK, or will I have memory problems? Also, is there a way to get the Embarcadero complex math functions to run faster? And finally, although its not terribly important to me, is this reinterpret_cast portable?

like image 564
user5108_Dan Avatar asked Oct 10 '13 15:10

user5108_Dan


1 Answers

This is allowed. Whilst this isn't a standard quote, cppreference has this to say:

For any pointer to an element of an array of complex numbers p and any valid array index i, reinterpret_cast<T*>(p)[2*i] is the real part of the complex number p[i], and reinterpret_cast<T*>(p)[2*i + 1] is the imaginary part of the complex number p[i].

I will look for the quote from the actual standard soon.

like image 51
Simple Avatar answered Oct 19 '22 10:10

Simple