Is there any advantage to using pow(x,2) instead of x*x, with x double?

FWIW, with gcc-4.2 on MacOS X 10.6 and -O3 compiler flags,

x = x * x;

and

y = pow(y, 2);

result in the same assembly code:

#include <cmath>

void test(double& x, double& y) {
        x = x * x;
        y = pow(y, 2);
}

Assembles to:

    pushq   %rbp
    movq    %rsp, %rbp
    movsd   (%rdi), %xmm0
    mulsd   %xmm0, %xmm0
    movsd   %xmm0, (%rdi)
    movsd   (%rsi), %xmm0
    mulsd   %xmm0, %xmm0
    movsd   %xmm0, (%rsi)
    leave
    ret

So as long as you’re using a decent compiler, write whichever makes more sense to your application, but consider that pow(x, 2) can never be more optimal than the plain multiplication.

Leave a Comment