The dreaded "^" function

I have recently come to a deep-seated hatred for the "^" function. In C++ this is known as "pow". The main reason isn't because it is a bad function, it's just really really slow. Here is an example:

Contents

To an integer power

x=2.1;
tic
for i = 1:100000
   y = (x+1)^4;
end
caret_time = toc;

tic
for i = 1:100000
   y = (x+1)*(x+1)*(x+1)*(x+1);
end
mult_time = toc;

It might be surprising to know that the value of "caret_time" on my computer is 0.0283 seconds while "mult_time" was .00095816. A factor of 30 faster. This is because before Matlab can multiply the thing 4 times with the "^" function, it has to interpret the power first. In other words, it has to figure out that there is a "4" being used before it can multiply four times.

As is turns out for things to the power of 2 or things of power 0.5 (using sqrt instead of pow), they end up being around the same amount of time.

To a non integer power

x=2.1;
tic
for i = 1:100000
   y = (x+1)^2.5;
end
caret_time = toc;

tic
for i = 1:100000
   y = (x+1)*(x+1)*sqrt(x+1);
end
mult_time = toc;

Whenever you have something to the N + 0.5 power, it is always faster to write it out as thing*thing N times then times sqrt. This is because the sqrt fucntion is implemented in the hardware of most modern processors, where is evaluating something to the N + 0.5 power is not. Instead it has to a non-hardware based root solving scheme.

caret_time = .0182, mult_time = .0016, 11.3 times faster

To a negative power

x=2.1;
tic
for i = 1:100000
   y = (x+1)^(-2);
end
caret_time = toc;

tic
for i = 1:100000
   y = 1/((x+1)*(x+1));
end
mult_time = toc;

Results of the negative power test:

caret_time = .0146, mult_time = .0006374, 22.9 times faster