When developing parfor loops it is typically best to start off in a serial loop to test with small data set and then add the "par" to scale to large sample set etc. When running serially it is great to get diagnostic information about each iteration of the for loop however when using the parfor loop for huge data set diagnostic information should be turned off.
So the question: is there any way to programmatically detect if executing in a for loop vs. a parfor loop? This way could so something like if ~isParfor; fprintf(...); end
Yes you can! Using getCurrentTask tells you whether the operations executing are being done on a worker or not. Check this code for a simple demonstration:
clc
clear all
A1 = zeros(10,10);
A2 = zeros(10,10);
Check1 = zeros(1,10);
Check2 = zeros(1,10);
parfor ix = 1:10
Check1(ix) = ~isempty(getCurrentTask());
myTemp = zeros(1,10);
for jx = 1:10
myTemp(jx) = ix + jx;
end
A1(ix,:) = myTemp;
end
clear myTemp
for ix = 1:10
Check2(ix) = ~isempty(getCurrentTask());
myTemp = zeros(1,10);
for jx = 1:10
myTemp(jx) = ix + jx;
end
A2(ix,:) = myTemp;
end
Check1
Check2
Outputs this:
Check1 =
1 1 1 1 1 1 1 1 1 1
Check2 =
0 0 0 0 0 0 0 0 0 0
Therefore it would be possible to check only the first entry of the 'Check' variable (i.e. at the first iteration in either case) and deduce whether you are (1) or not (0) in a parfor loop.