Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a parallel loop?

You'd think this would be simple question, but I can't find the solution. Take the following loop:

A = zeros(1,10000000);
parfor i = 1:length(A)
    A(i) = i;
end

This only runs on a single core on my computer, although it's readily parallelisable (or at least it should be). I am using Matlab 2012b, and I've tried looking for documentation on how to create parallel loops but can't find any (the matlab docs just show examples of how to create these loops, not how to actually run them in parallel).

I've tried looking up how to modify parallel computing toolbox settings, but none of them work since they're all for Matlab 2013 (I'm using 2012b). If someone could provide an example of a trivial, parallelisable loop that actually runs in parallel I would be very grateful!

Note: I have checked and the parallel computing toolbox is installed, although I have no way of knowing if it is enabled, or how to enable it, since the documentation doesn't seem to provide an answer to this for my version (I typed preferences into the command prompt but didn't see it there).

EDIT: I got it working by doing this:

matlabpool('open',4);
A = zeros(1,10000000);
parfor i = 1:length(A)
    A(i) = i;
end
matlabpool('close');

... but I don't really know why this works, whether I have close the pool every time, what a pool actually is (I've read the documnentation, still don't get it), and how matlabpool differs from parpool...

like image 996
quant Avatar asked Oct 02 '13 06:10

quant


3 Answers

Like I said in my comment, you need to launch the MATLAB workers:

matlabpool open N

The parpool command replaced the matlabpool command in version R2013b. The command creates a number of local workers (assuming your default cluster is the local profile), which are simply MATLAB.exe processes running without a GUI, that execute parts of parallelized code, like your parfor loop.

like image 181
chappjc Avatar answered Sep 29 '22 10:09

chappjc


It is not necessary needed to close the pool. In some cases you may wish to keep it open for later reuse (as opening also takes some time). Testing for a zero pool size can be helpful to decide, if a new matlabpool needs to be open:

A = zeros(1,10000000);
if matlabpool('size') == 0 
   matlabpool('open',4) ;
end
parfor i = 1:length(A)
    A(i) = i;
end
like image 36
BHF Avatar answered Sep 29 '22 11:09

BHF


Since the change from matlabpool to parpool, there is an even easier way to create the pool. Unlike parpool, it doesn't throw an error if the pool already exists. Just call gcp (which stands for "get current pool").

gcp();
A = zeros(1,10000000);
parfor i = 1:length(A)
    A(i) = i;
end

It is good practice to always leave the pool open; this just ensures that it's open when you need it.

like image 21
Jotaf Avatar answered Sep 29 '22 10:09

Jotaf