slow re-assignment of values to an array in a structure

Here is my problem: Why does line 6 below take two orders of magnitude more time to compute than other instances of the same command?
1.>> x = ones(100,100,250);
2.>> tic; x(:,:,23) = rand(100,100) ; toc
Elapsed time is 0.000433 seconds.
3.>> tic; x(:,:,23) = rand(100,100) ; toc
Elapsed time is 0.000420 seconds.
4.>> tic; x(:,:,23) = rand(100,100) ; toc
Elapsed time is 0.000417 seconds.
5.>> s.x = x;
6.>> tic; x(:,:,23) = rand(100,100) ; toc
Elapsed time is 0.013906 seconds.
7.>> tic; x(:,:,23) = rand(100,100) ; toc
Elapsed time is 0.000435 seconds.
8.>> tic; x(:,:,23) = rand(100,100) ; toc
Elapsed time is 0.000537 seconds.
*******
In my application I send a large structure of arrays into a subroutine and I observe it running super slowly and I think this is the issue.
Any explanation?

 Réponse acceptée

Sorry, at first I didn't read the whole question.
My guess is that line 5 doesn't actually copy the data in x. When you change x the copy happens. Before the copy happens, s.x only "points" to the values in x. This is a MATLAB "efficiency" known as copy-on-write.
See Loren's response number 6.
.
.
EDIT
Here is how really to see this:
format debug
x = [2,2] % Look at pr, this is the pointer in memory
s.x = x; % Make assignment...
s.x % Same pr here as above for x.
% Now change x and look at the pointers...
x = 5; % Make change.
x
s.x % Different pr now

3 commentaires

Exactly.
If you put tic/toc around steps 1 and 5, you'll notice that step 5 takes very little time because it's not really creating a copy of "x". and the extra amount of time taken in step 6 is comparable to the amount of time it takes to create an array of ones (step 1).
Nice approach, Jiro! Here is even more evidence of what happens, as if we needed any at this point:
>> clear all, pack
>> tic,x = rand(10000);toc
Elapsed time is 5.906108 seconds.
>> tic,y = x;toc
Elapsed time is 0.000041 seconds.
>> tic,x(1) = 3;toc
??? Out of memory. Type HELP MEMORY for your options.
Now you just gotta ask, how could this have run MATLAB out of memory?
Nice.

Connectez-vous pour commenter.

Plus de réponses (1)

Jonathan
Jonathan le 10 Avr 2011

0 votes

Thanks guys! Much appreciated. So it is the accursed "copy on write" thing. If only I could pass array pointers to Matlab subroutines.....

Catégories

En savoir plus sur Startup and Shutdown dans Centre d'aide et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by