I have been learning about the impact of cache size on code performance. I wrote a small code to see how using a column major loop in MATLAB would be better than using a row major loop, since MATLAB stores matrices in column major like FORTRAN. I also compared against MATLAB's internal multiplication routine. Here is the code and the results:
% row major access tic for i=1:n for j=1:n b1(i)=b1(i)+A(i,j)*x(j); end end t1(count)=toc; % column major access tic for j=1:n for i=1:n b2(i)=b2(i)+A(i,j)*x(j); end end t2(count)=toc; % column major vector ops tic for i=1:n b3(i)=b3(i)+A(i,:)*x(:); end t3(count)=toc; % row major vector ops for j=1:n b4(:)=b4(:)+A(:,j)*x(j); end t4(count)=toc; % MATLAB built in tic b5=A*x; t5(count)=toc; % double vop tic b6=A(:,:)*x(:); t6(count)=toc;
The column major loop is faster than the row major loop, but how is MATLAB so much faster?