Why the preallocated matrix perform slower in the case below?
조회 수: 3 (최근 30일)
이전 댓글 표시
I have a situation where I have to create a matrix and do some analysis on it. However the matrix size changes frequently. I thought if I preallocate the matrix to the largest size and then use a portion of it to do the analysis, it might be faster. Before implementation, I tried this out as following:
clear;
clc;
nx = 1000;
nn = randi(500,nx,1);
tic;
for j = 1:nx
ZZ = rand(nn(j));
end
toc;
tic;
ZZn = zeros(500);
for j = 1:nx
%n = randi(100);
ZZn(1:nn(j),1:nn(j)) = rand(nn(j));
end
toc;
The first portion does not preallocate ZZ and create it dynamically while the second one only uses as piece of the preallocated ZZn matrix. On test, I get
Elapsed time is 1.112910 seconds.
Elapsed time is 1.193189 seconds.
I have tested this many times with varying loop amounts. I hope someone can explain this and if I'm doing something I should not, point me towards the right direction.
댓글 수: 0
답변 (2개)
Patrik Ek
2014년 2월 6일
편집: Patrik Ek
2014년 2월 6일
I am not 100% sure about this but I think that when performing the step ZZ = rand(nn(j)), matlab allocates more memory to store the data from rand. Then matlab delete the old data clearing memory and moving the pointer to the to point at the new data instead. This is not so different from case 2. Using rand the same way matlab still needs to allocate new memory, moving pointers and delete the old data. Assigning a variable as you do in case 1 should not be the same as building up a matrix step by step, which also requires that all the old matrix values are copied as well.
Please correct me if I am wrong.
댓글 수: 0
Jos (10584)
2014년 2월 6일
You are not doing the same thing, as it takes time to evaluate the indices into ZZn, as well as temporary memory to store them.
For a valid comparison, you should change the first for-loop into
for ...
1:nn(j) ; 1:nn(j)) ; % takes time and memory
ZZ = rand(nn(j));
end
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Performance and Memory에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!