Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A concrete example of a parfor loop in Matlab that outperforms the for loop

I am still somewhat new to parallel computing in Matlab. I have used OpenMP in C successfully, but could not get better performance in Matlab.

First, since I'm machine at a university that I am new to, I verified that the machine I am on has the Parallel Computing Toolbox by typing ver in the command prompt and it displayed: Parallel Computing Toolbox Version 5.2 (R2011b). Note that the machine has 4 cores

I tried simple examples of using parfor vs. for, but for always won, though this might be because of the overhead cost. I was doing simple things like the example here: MATLAB parfor is slower than for -- what is wrong?

Before trying to apply parfor to my bigger more complicated program (I need to compute 500 evaluations of a function and each evaluation takes about a minute, so parallelizing will help here), I would very much like to see a concrete example where parfor beats for. . Examples are abundant for OpenMP, but did not find a simple example that I can copy and paste that shows parfor is better than for

like image 615
db1234 Avatar asked Nov 22 '25 16:11

db1234


2 Answers

I use the following code (once per Matlab session) in order to use parfor:

pools = matlabpool('size');
cpus = feature('numCores');
if pools ~= (cpus - 1)
    if pools > 0
        matlabpool('close');
    end
    matlabpool('open', cpus - 1);
end

This leaves 1 core for other processes. Note, the feature() command is undocumented.

like image 197
Serg Avatar answered Nov 25 '25 11:11

Serg


There is an example of improved performance from parfor on Loren Shure's MATLAB blog.

Her example is simply computing the rank of a magic square matrix:

function ranks = parMagic(n)

ranks = zeros(1,n);
parfor (ind = 1:n)
    ranks(ind) = rank(magic(ind));  % last index could be ind,not n-ind+1
end
like image 30
cjh Avatar answered Nov 25 '25 11:11

cjh