(The following takes place on a Macbook Pro 2.3GHz i7 Haswell with 16GB RAM)
Issue
In Matlab I have a 3D-data processing algorithm. In this case a three-way nested loop where the dimensions are on the scale of <1000 values per vector (ie z<1000, y<1000, x<1000). For each voxel a dynamic set of calculations are performed. When executed from the Matlab command line the speed of the algorithm is good. It runs as can be expected on a relatively high-end machine.
When I move this very same code (copy & paste) into a GUIDE GUI callback function (a Button) generated by Matlab the rate of execution slows to an absolute crawl. It is not 1/10th or even 1/100th the normal rate. Possibly it's closing in on 1/1000th the normal rate... or something of that order.
Thoughts
So my initial thoughts are that this radical performance hit must be comming from the GUI somehow. So I tried to implement the parfor
Matlab keyword in order to run the computationally intensive for loop in parallel. This was not possible since any variable created inside the parfor
-loop cannot be used outside of it. Or at least that is how I interpret the Matlab error that I get when trying to use that method.
I also tried spawning the calculation in a new thread but did not seem to improve performance in any way.
Question
My question: Is there a certain way that computationally intensive tasks should be executed when running from a Matlab GUI?
Addition
Pseudo code of this situation. The following Matlab functions are used inside the loop: max(), abs(), sqrt(), zeros(), mod(), fprintf() Please note that the use of fprintf() is NOT excessive and I am aware that excessive calls to functions like this could result in a performance penalty.
for-loop
fprintf(1,'%d ',i);
if (mod(i,20)==0)
fprintf(1,'\n'); % output iteration status
end
for-loop
for-loop
some variable assignments
declare variables and init them to 1 or 0
for-loop Xvar
if ((condition)) <= 0.0
variable assignment
end
if ((condition)) <= 0.0
variable assignment
end
end
for-loop Yvar
if ((condition)) <= 0.0
variable assignment
end
if ((condition)) <= 0.0
variable assignment
end
end
for-loop Zvar
if ((condition)) <= 0.0
variable assignment
end
if ((condition)) <= 0.0
variable assignment
end
end
somevariable=zeros(args);
for-loop
multiplication assignment to variable
multiplication assignment to variable
variable assignment
for-loop
for-loop
for-loop
sqrt calculation with some divisions and squares
if-statement
subtraction addition assignment
if-statement
var=some other var;
end
end
end
end
end
somevarindexed(m)=stuff calculated above;
end
variable assignment;
3Dvector(x,y,z) assignment;
3Dvector(x,y,z) assignment;
end
end
end