Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matlab parfor leads to larger execution time than a for loop

I have a 3 dimensional grid, in which for each point of the grid I want to calculate a time dependent function G(t) for a large number of time steps and then summing the G function for each grid point. Using 4 for loops the execution time is becoming very large, so I am trying to avoid this using parfor.

a part of my code:

for i=1:50
    for j=1:50
        for k=1:25
            x_in=i*dx;
            y_in=j*dy;
            z_in=k*dz;
            %dx,dy, dz are some fixed values
            r=sqrt((xx-x_in).^2+(yy-y_in).^2+(zz-z_in).^2);
            %xx,yy,zz are 50x50x25 matrices generated from meshgrid
            % r is a 3d matrix which produced from a 3 for-loop, for all the points of grid
            parfor q=1:100
                t=0.5*q;
                G(q)=((a*p)/(t.^1.5)).*(exp(-r.^2/(4*a*t)));
                % a,p are some fixed values
            end
            GG(i,j,k)=sum(G(:));
        end
    end
end

When I am using parfor the execution time becomes larger, and I am not sure why this is happening. Maybe I am not so familiar with sliced and indexed variables on a parfor loop.

My pc processor has 8 threads and ram memory ddr3 8GB

Any help will be great.

Thanks

like image 750
george Avatar asked Dec 12 '25 21:12

george


1 Answers

As has been discussed in a previous question, parfor comes with an overhead. Therefore, loop that is too simple will execute more slowly with parfor.

In your case, the solution may be to parallelize the outermost loops.

%# preassign GG
GG = zeros(50,50,25);

%# loop over indices into GG
parfor idx = 1:(50*50*25)
    [i,j,k] = ind2sub([50 50 25],idx);
    x_in=i*dx;
    y_in=j*dy;
    z_in=k*dz;
    %dx,dy, dz are some fixed values

    r=sqrt((xx-x_in).^2+(yy-y_in).^2+(zz-z_in).^2);

    %xx,yy,zz are 50x50x25 matrices generated from meshgrid
    % r is a 3d matrix which produced from a 3 for-loop, for all the points of grid

    for q=1:100
        t=0.5*q;
        G(q)=((a*p)/(t.^1.5)).*(exp(-r.^2/(4*a*t)));
        % a,p are some fixed values
    end
    GG(idx)=sum(G(:));
end
like image 150
Jonas Avatar answered Dec 15 '25 08:12

Jonas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!