Which of the two methods is faster

2 ビュー (過去 30 日間)
Kaushlender Kumar
Kaushlender Kumar 2019 年 2 月 19 日
編集済み: Kaushlender Kumar 2019 年 2 月 23 日
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.

回答 (1 件)

Pranjal Priyadarshi
Pranjal Priyadarshi 2019 年 2 月 22 日
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.

カテゴリ

Help Center および File ExchangeMultidimensional Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by