3

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

jpjacobs
  • 9,359
  • 36
  • 45
george
  • 33
  • 4

1 Answers1

6

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
Community
  • 1
  • 1
Jonas
  • 74,690
  • 10
  • 137
  • 177
  • 1
    Or even a single parfor i=1:50, in case there is still an overhead – Andrey Rubshtein Feb 28 '12 at 12:58
  • You can check if the overhead is affected by the number of workers. For a small job, fewer workers can be sufficient – zamazalotta Feb 28 '12 at 13:03
  • thanks @Jonas for the answer and thank you all for your comments. I focus in the inside loop and didn't think about the outermost loops. zamazalotta i 'll try it. – george Feb 29 '12 at 07:52