I am rally confused. Why parfor is slower than for in this very simple test situation?

1 view (last 30 days)
tic
A = 1:100;
B = 1:100;
Nx = 500;
Ny = 500;
x_values = linspace(0,1,Nx);
y_values = linspace(0,1,Ny);
collected_data = zeros(Nx,Ny);
parfor ix = 1:Nx
x = x_values(ix);
for iy = 1:Ny
y = y_values(iy);
collected_data(ix,iy) = exp(sum(A*x+B));
end
end
toc
Elapsed time is 1.121132 seconds. (with 2 workers)
But: Elapsed time is 0.149634 seconds. (with for instead of parfor)
  1 Comment
Adam
Adam on 5 Jan 2018
Edited: Adam on 5 Jan 2018
Parallelisation can be a bit of a black art when it comes to working out how to optimise it and when it is worth using. There is an overhead to copying data to and from workers. If the computation being done is not sufficiently complex to balance that out then the data transfer time will outweigh the computation time.
Coming up with a 'simple test situation' for parfor, therefore, is not always trivial as it cannot be too simple if you want to compare timings.
Also, in your case, when I put that code into a file I get a warning about y_values being a broadcast variable. You shouldn't ignore warnings if you care about speed!

Sign in to comment.

Answers (0)

Categories

Find more on Parallel for-Loops (parfor) in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!