MATLAB: ‘parfor’ slower than ‘for’

parfor

Dear Matlab community,I'm just not quite clear why 'parfor' won't work, or what I can do to make my program faster. Here is the code.
for i=1:M
parfor j=1:N
[temp_node(i,j,:)]=node_automatron(node_table(i,j,:),i,j);
end
end
parfor i=1:size(path_table,1)
[temp_path_table(i,:),node_act_1,node_act_2]=path_automatron(path_table(i,:),node_table{path_table{i,2}(1),path_table{i,2}(2),7},node_table{path_table{i,3}(1),path_table{i,3}(2),7});
node_act(i,:)=[node_act_1,node_act_2];
end
Result time is about 6 seconds, 4seconds slower than when I use 'for' loop. I also tried to run other program, which 'parfor' loop is indeed faster than 'for' loop.
Thank you.

Best Answer

Hey Wu,
You may find this documentation page useful for helping decide if parfor is useful in your application, and how to best apply it.
The starting and stopping of a parallel pool of workers will also add to the overhead of using parfor. If you are planning on running parallel code multiple times in a row, you may wish to explicitly start and manage the parallel pool outside of the code you are running.
It's unclear to us what node_automatron and path_automatron do, or how big the node_table and path_table are. You may be better served by making those functions "vectorized" or otherwise able to operate on input arrays so that you can avoid loops entirely. Here is some basic information on vectorized code, though yours will probably be a more advanced maneuver due to the multi-dimensional arrays you are using.
Hope this helps!
-Cam