479Memory-Related Techniques
for yIdx = 1:size(data,2)
total = total + data(xIdx,yIdx,zIdx);
end
end
end
⇨ Elapsed time is 0.665435 seconds.
% Much better - permute dimensions: loop over z,y,x (5x faster)
data = permute(data, [3,2,1]); % in-place to prevent memory spikes
for zIdx = 1:size(data,3)
for yIdx = 1:size(data,2)
for xIdx = 1:size(data,1)
total = total + data(xIdx,yIdx,zIdx);
end
end
end
data = permute(data, [3,2,1]); % reshape back to original
⇨ Elapsed time is 0.137673 seconds.
Loop order effects can also be seen with internal MATLAB code, even in cases where we
might expect implicit parallelization to negate such effects. For example, ( B'*A')' might
be faster than the equivalent A*B., if A has many m