Which of the two methods is faster

1 Ansicht (letzte 30 Tage)
Kaushlender Kumar
Kaushlender Kumar am 19 Feb. 2019
Bearbeitet: Kaushlender Kumar am 23 Feb. 2019
x1 = single(10);
x2 = single(30);
n = 7;
[r1 r2] = ratio(x1,x2,n);
[r1 r2]
function [r1 r2] = ratio(x1,x2,n)
tic
r1 = zeros(n,1,'single');
r2 = r1;
for k = 1:n
r1(k) = x1^(2^k)/x2^(2^k);
r2(k) = (x1/x2)^(2^k);
end
toc
end
Present the results from running the above driver program. Since
(1) is true, one can conclude that the two methods r1 and r2 should give
identical results. Explain why this is not true as the values of k
increase.

Antworten (1)

Pranjal Priyadarshi
Pranjal Priyadarshi am 22 Feb. 2019
There is no evidence that vectorized code is faster in general.
If a build-in function can be applied to a complete array, a vectorization is much faster than a loop approach. When large temporary arrays are required, the benefits of the vectorization can be dominated by the expensive allocation of the memory, when it does not match into the processor cache.
A secondary effect of vectorizing is that the code looks clearer.
As the value of k increases the benefit that vectorization provides diminishes as it is no more possible to cache the large array. In order to be time efficient, we can better use data structures present in the MATLAB library like tall arrays or datastores.

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by