strange performance behavior - microbenchmark
Afficher commentaires plus anciens
There are two implementations of the same algorithm:
function B = alg1( B, R, alpha )
% Fast computation of L1 distance transform
K = numel(B);
% forward pass
for k=2:K
B(k) = min( B(k), B(k-1) + alpha * (R(k) - R(k-1)));
end
% backward pass
for k=K-1:-1:1
B(k) = min( B(k), B(k+1) + alpha * (R(k+1) - R(k)));
end
end
and
function B = alg2( B, R, alpha )
% Fast computation of L1 distance transform
alphaRdiff = alpha*diff(R);
K = numel(B);
% forward pass
for k=2:K
B(k) = min( B(k), B(k-1) + alphaRdiff(k-1));
end
% backward pass
for k=K-1:-1:1
B(k) = min( B(k), B(k+1) + alphaRdiff(k));
end
end
These two algorithms differs only by elimination of term
alpha * (R(k) - R(k-1)))
from the both for-loop.
And by scaled differences pre-computation of vector R
alphaRdiff = alpha*diff(R);
So, the second algorithm alg2 should be faster, because only half of multiplications alpha*(R(k)-R(k-1)) is performed.
But speed of both algorithm is still nearly same (or unmodified alg 1 is even faster), see
N = 1e5;
B = rand(1,N);
R = rand(1,N);
tic;A = alg1( B, R, 1/3 );toc
tic;A_= alg2( B, R, 1/3 );toc
isequal(A,A_)
Elapsed time is 0.037654 seconds.
Elapsed time is 0.029562 seconds.
ans =
logical
1
N = 1e8;
tic;A = alg1( B, R, 1/3 );toc
tic;A_= alg2( B, R, 1/3 );toc
Elapsed time is 1.444549 seconds.
Elapsed time is 1.563630 seconds.
What is the explanation of this strange behavior?
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Sources dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!