multiplication by 0.5 vs division by 2
Show older comments
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 Comments
John D'Errico
on 28 Sep 2019
First, tic and toc are TERRIBLE ways to test the time of something. They are too subject to problems. TIMEIT is a slightly safer choice, although any time estimate will not be perfect, since your computer does other random crap on the side all the time.
In some cases (and we cannot know which applies) the code parser may do some optimization. For example, a divide by 2 or a multiply by 2 might be special cased, since all numbers are stored in binary form.
Anyway, special cases under the hood in the parser are not something we can worry about. Nor are 10% differences in speed, because they may be different if you run this on a different CPU, or a different MATLAB release.
Walter Roberson
on 29 Sep 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.)
Answers (0)
Categories
Find more on Performance and Memory in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!