multiplication by 0.5 vs division by 2
11 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
I tried the following with two options - matrix and scalar
clear;
N = 1e7;
tic
for n = 1:N
% a=[n n;n n]/2;
a = n/2;
b = a/2;
end
toc
clear;
N=1e7;
tic
for k=1:N
% c=[k k;k k]*0.5;
c=k*0.5;
d=c*0.5;
end
toc
clear;
N=1e7;
tic
for m=1:N
%f=[m m;m m]/1.41;
f=m/1.41;
g=f/1.41;
end
toc
clear;
N=1e7;
tic
for t=1:N
% p=[t t;t t]*1.41;
p=t*1.41;
q=p*1.41;
end
toc
And after the second run (the first run is similar) I got the following results. For a matrix:
Elapsed time is 10.591345 seconds.
Elapsed time is 12.099287 seconds.
A*0.5 is slightly slower than A/2
Elapsed time is 12.162518 seconds.
Elapsed time is 10.652158 seconds.
A*1.41 is slightly faster than A/1.41.
For a scalar:
Elapsed time is 0.024380 seconds.
Elapsed time is 0.017146 seconds.
almost no difference between A/2 and A*0.5
Elapsed time is 0.150341 seconds.
Elapsed time is 0.017156 seconds.
finally, A*1.41 is sufficiently faster than A/1.41.
I was taught that multiplication is always much faster than division. Could you please explain me how this works in Matlab?
4 Commenti
Walter Roberson
il 29 Set 2019
MATLAB does treat 0.5 as a special case.
x1 = rand(1,100000);
>> timeit(@() x1.^0.5,0)
ans =
0.000712931948
>> timeit(@() x1.^0.12345,0)
ans =
0.002301166963
However, at another level it is fair to ask whether it really recognizes 0.5 as a special case, or if instead the power algorithm is iterative and it so happens that the 0.5 case satisfies the iterations quickly. To answer that we can look at the 0.25 case, which you would expect to be roughly twice as long as the 0.5 case if you are doing iteration (because 0.25 is two iterations of 0.5). It turns out that the 0.25 case takes approximately the same time as the 0.12345 case, possibly even a little longer (the difference is down in the range where you would want to measure quite a number of times to see if the differences are statistically significant or are only due to chance.)
Risposte (0)
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!