Speed Optimization on Fix Matrix Looping
Ben Abbott
bpabbott at mac.com
Sun May 4 14:01:16 CDT 2008
On May 4, 2008, at 2:31 PM, lain.ux wrote:
> Hi,
>
> I have tried to run my octave code with following two test cases and
> gotten the elapsed time. As the result, test case 2 is executed much
> faster than case 1.
>
> Case 1:
> b = [];
> for i = 1:N
> b(i, 1:P) = i * ones (1, P);
> endfor
>
> Case 2:
> b = 1.0 * ones (N, P); # this line doesn't effect the final matrix b
> # value. but with this line, the execution time
> # becomes much-much faster
> for i = 1:N
> b(i, 1:P) = i * ones (1, P);
> endfor
>
> My platform:
> - Processor: Intel Core 2 Duo
> - Operating System: Debian GNU/Linux 4
> - Octave Version: 3.0.1
>
> My questions are:
> 1) Is the test result correct?
> 2) Has anyone test about it?
>
> Suggestion:
> I see that b = []; is mostly used on Octave codes. If the result is
> correct (can improve the speed), I think, it better to be changed
> automatically during the parsing step so needless for user to change
> the
> line manually.
>
> Please find the complete test code and result from my blog:
> http://l411v.blogspot.com/2008/04/octave-speed-
> optimization-080426.html
>
> Thanks,
> lain.ux
In the faster one, you have preallocated memory for "b".
In the first case, allocation/reallocation takes place on each loop.
You might compare to
> for i = N:-1:1
> b(i, 1:P) = i * ones (1, P);
> endfor
which should be just as fast as when preallocated.
Regarding an automatic preallocation, I don't think it is possible to
do so it a universally robust way.
Ben
More information about the Help-octave
mailing list