Speed Optimization on Fix Matrix Looping
lain.ux
l411v.ux at gmail.com
Sun May 4 15:39:07 CDT 2008
Ben Abbott wrote:
>
> 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
Hi Ben,
Thanks for the answer. I have retest the cases, now, it's including your
suggestion. The result as follow:
- Without preallocation is 40 seconds
- With preallocation is 0.1 second
- With changing the looping sequence (as you suggested) is 0.13 second
I have also update my blog:
http://l411v.blogspot.com/2008/04/octave-speed-optimization-080426.html
Thanks,
lain.ux
More information about the Help-octave
mailing list