4

I stumbled upon the answer of Matt in a thread about creating identity matrices with Matlab. He uses

A(N,N) = 0

to allocate a NxN matrix with zero entries. I've always used

A= zeros(N)

I was wondering, which of the two ways is faster and have written the following small test script.

function compare


N =2.^[1:14];


T1 = zeros(length(N),1);
for i=1:length(N)
    clear A
    n =N(i);
    tic
    A(n,n) = 0;
    t=toc;
    T1(i) = t;
end

T2 = zeros(length(N),1);
for i=1:length(N)
    clear A
    n =N(i);
    tic
    A=zeros(n);
    t=toc;
    T2(i) = t;
end




figure
loglog(N,T1,'r');
hold on
loglog(N,T2,'g');
title('Runtime for memory allocation');
legend('A(N,N)=0', 'A=zeros(N)','Location','SouthEast');
xlabel('N');
ylabel('Runtime')


end

Which simply measures the time for memory allocation via the two different ways. Here is the result:

enter image description here

This means, that for small N, both methods are equally fast, but for N>1000, the time to allocate a matrix with A(N,N)=0 actually drops? I'm unable to explain this result and would be happy to hear some opinions on this.

Thanks!

Community
  • 1
  • 1
Thomas
  • 1,199
  • 1
  • 14
  • 29
  • 3
    Check out [this](http://undocumentedmatlab.com/blog/preallocation-performance) post from Yair Altman's website that's quite interesting and should answer a few interrogations – Benoit_11 Jul 28 '15 at 11:43
  • Thanks, this explains why one method is faster than the other. However, I'm still not sure what's happening at N=1000? – Thomas Jul 28 '15 at 11:49
  • It's likely going to be difficult for anyone to answer that question without having knowledge of MATLAB's internals. – sco1 Jul 28 '15 at 11:57
  • To be honest I have no idea haha maybe someone here will enlighten us :) – Benoit_11 Jul 28 '15 at 11:57
  • 1
    http://stackoverflow.com/questions/14169222/faster-way-to-initialize-arrays-via-empty-matrix-multiplication-matlab – Jens Boldsen Jul 28 '15 at 12:12
  • 2
    @Benoit_11 The results of the OP is very consistent with the page you referenced, and also with [this one](http://undocumentedmatlab.com/blog/allocation-performance-take-2). He argues about some effect of SIMD ... not the reason IMO. Hope a Mathworks guy will hear you ... :) – Bentoy13 Jul 28 '15 at 12:13
  • @JensBoldsen Following one of the answer, the reason seems to lie under the allocation scheme of the OS. I tend to agree with it ... but I cannot find it, need more search. – Bentoy13 Jul 28 '15 at 12:23

0 Answers0