Effacer les filtres
Effacer les filtres

Which of the two methods is faster

4 vues (au cours des 30 derniers jours)
Kaushlender Kumar
Kaushlender Kumar le 19 Fév 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.

Réponses (1)

Pranjal Priyadarshi
Pranjal Priyadarshi le 22 Fév 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.

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by