[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Structures and tensors
From: |
JFC |
Subject: |
Re: Structures and tensors |
Date: |
Tue, 1 Aug 2006 18:08:20 +0000 (UTC) |
User-agent: |
Loom/3.14 (http://gmane.org/) |
Cédric Févotte <cedric.fevotte <at> mist-technologies.com> writes:
> What are the general recommandations about the use of structures and
> tensors in Octave ? Understand, is it recommanded to avoid them ?
I was about to post about the same issue but was thinking of posting
to the bug list... Indeed, I have just realized that assignment to a
vector which is a field in a structure may be horribly slower
than assigning to a "stand-alone vector".
I append some code demonstrating this effect. I have three functions
which do the same thing: return a structure which contains only a
zero-vector. This vector is set to zero by looping over sub-vectors.
Function 1 creates the vector, fills it, append it to the structure.
Function 2 creates the structure, allocates space for the vector as a field
in the structure, fills it using the same loop. Muuuuch slower for large sizes.
Function 3 shows that the slow down is of the same order of magnitude as what
happens when one "forgets" to pre-allocate memory (the vector is
repeatedly resized in the loop).
Here is the result for 2.1.73 on a standard Intel machine.
octave> speedtest
Speed tests
Size 100 | t1= 58 | t2= 127 | t3= 68 |
Size 200 | t1= 78 | t2= 679 | t3= 304 |
Size 300 | t1= 90 | t2= 1493 | t3= 700 |
Size 500 | t1= 131 | t2= 3610 | t3= 1806 |
Size 800 | t1= 194 | t2= 8430 | t3= 4366 |
octave>
The code to generate this is appended below.
Cheers, JF
clear;
################################################################
function Modes = f1 (n)
## Fast version
Data = zeros(n^2,1);
range=1:n;
for ell=1:n
Data(range) = zeros(n,1) ;
range=range+n;
endfor
Modes.data = Data ;
endfunction
################################################################
function Modes = f2 (n)
## Slow version: assignment to a structure field
Modes.data = zeros(n^2,1);
range=1:n;
for ell=1:n
Modes.data(range) = zeros(n,1) ;
range=range+n;
endfor
endfunction
################################################################
function Modes = f3 (n)
## Slow: As f1 but no pre-allocation of a big vector
range=1:n;
for ell=1:n
Data(range) = zeros(n,1) ;
range=range+n;
endfor
Modes.data = Data ;
endfunction
################################################################
function speedcomp(n)
tic ; f1(n) ; t1=toc ; t1 = fix(10^6*t1/n);
tic ; f2(n) ; t2=toc ; t2 = fix(10^6*t2/n);
tic ; f3(n) ; t3=toc ; t3 = fix(10^6*t3/n);
printf("Size %4i | t1=%6i | t2=%6i | t3=%6i |\n", n, t1, t2, t3 );
endfunction
################################################################
printf("Speed tests\n");
for n = [ 100 200 300 500 800 ]
speedcomp(n);
endfor
################################################################