Why does overwriting the whole matrix take so long?

3 views (last 30 days)
JS
JS on 17 May 2015
Commented: JS on 18 May 2015
I have code that in concept looks like this and takes very long to run:
clear all
tic
[A,B] = ndgrid(1:10^4,1:10^4);
for ind = 1:numel(A)
C = A(ind)*B(ind);
end
C = A.*B;
toc
Elapsed time is 26.513977 seconds.
First I tried this code (added a line before final multiplication) because C changed size in my actual code, but it didn't improve:
clear all
tic
[A,B] = ndgrid(1:10^4,1:10^4);
for ind = 1:numel(A)
C = A(ind)*B(ind);
end
C = zeros(size(A));
C = A.*B;
toc
Elapsed time is 26.368709 seconds.
However, clearing C instead worked:
clear all
tic
[A,B] = ndgrid(1:10^4,1:10^4);
for ind = 1:numel(A)
C = A(ind)*B(ind);
end
clear C
C = A.*B;
toc
Elapsed time is 2.157905 seconds.
Why is this? What's good practice to reduce runtime for such a case? I don't think I'm supposed to clear every variable before I recompute/overwrite it...
Thanks
  6 Comments
JS
JS on 17 May 2015
I'm not sure if I understood your comment properly, but I just tried entering the slow code line by line into the command window and it (the line C=A.*B;) was much faster, without clearing C first.
Jan
Jan on 17 May 2015
@JS: The JIT acceleration is applied in function M-files, while the code in the command window is not accelerated - at least this has been the case for many Matlab versions. Therefore dpb asks for the difference between the timings.

Sign in to comment.

Answers (1)

Jan
Jan on 17 May 2015
The JIT acceleration does not provide its full power if the size of a variable is changed. This has been discussed e.g. at http://www.mathworks.com/matlabcentral/answers/214625-matlab-jit-and-execution-time .
Your examply shows that clearing the variable before redifining it with a new size avoid the interference. Another method would be not to redefine variables.
tic
[A,B] = ndgrid(1:10^4,1:10^4);
for ind = 1:numel(A)
C = A(ind)*B(ind);
end
D = A.*B; % Not C !
toc
  6 Comments
dpb
dpb on 18 May 2015
"The size of the variable doesn't change"
Ah, but it does -- in the loop you're only computing the one term, overwriting C each pass thru the loop. Now that may not have been the intent, but that's the code as written...
JS
JS on 18 May 2015
Wow, I don't know how I could miss that... now the problem seems a little bit less weird to me :)

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!