I have rewrote my MATLAB function in C using mex and it++, but my mex implementation is a lot slower than my MATLAB function. I was wondering if anyone could tell me what I am doing wrong. MATLAB
for idx = 1:length(eps_r)
if (idx == 1) || (eps_r(idx) ~= eps_r(idx-1))
v_p = c/sqrt(eps_r(idx)); % m/s - Propogation Velocity
dz = v_p*dt/2;
k = 2*w/v_p; % rad/m
z_shift = exp(1i*dz*sqrt((repmat(k,1,size(data,2))).^2-(repmat(kx,size(data,1),1)).^2));
end
fk_data(idx,:) = ifft(mean(data))*exp(-1i*2*pi*freq(1)*time(idx));
data = data.*z_shift;
end
MEX with IT++
for(int idx = 0; idx < eps_r.size(); idx++ )
{
if ( (idx == 1) || (eps_r(idx) != eps_r(idx-1) ) )
{
v_p = 2.9979e+08 / sqrt(eps_r(0));
dz = v_p * time(0)/2;
k = 2 * w / v_p;
for(int y = 0 ; y < z_shift.size(); y++)
z_shift(y) = exp(dz * i * sqrt(pow(z_shift_pt1(y),2) - pow(z_shift_pt2(y),2)));
}
fk_data = ifft(complex_mean(data)) * exp(-i * 2 * itpp::pi * freq(0) * time(idx));
data = elem_mult(data,z_shift);
}
}
-O3or at least-O2) activated? Did you try to profile your mex function? - Thilo-O3optimization switch, that is gcc specific. For mex, the corresponding switch is-O. Also, mex turns on optimizations by default unless you use the-gswitch to suppress this. If you're using gcc to compile, you could try addingCOMPFLAGS="$COMPFLAGS -O3"(on Windows), it'sCFLAGSon UNIX (check the link). Lastly, MATLAB is very efficient when it comes to linear algebra, and it shouldn't be very surprising that your mex file is not able to beat it at its own game. - Praetorian