ofey
ofey

Reputation: 443

efficiency of pow(num,2)?

I need to calculate squares of floats many times.(to the order of 10^8)

Which is better (as time is a huge constraint) :

 pdt=pow(num,2);

      OR

 pdt=num*num

Or are they really same?

Edit: On checking both styles on reasonably large input, my processor gave contradictory results.

Upvotes: 1

Views: 205

Answers (2)

cmh
cmh

Reputation: 10927

Using gcc with no optmisations num * num is faster as pow incurs a function call. At -O2 they output identical asm (for x86):

float numpow(float x){
    return pow(x, 2);
}

float mulpow(float x){
    return x*x;
}

compiled with g++ -S -O2 -c 

__Z6numpowf:
Leh_func_begin1:
    pushq   %rbp
Ltmp0:
    movq    %rsp, %rbp
Ltmp1:
    mulss   %xmm0, %xmm0
    popq    %rbp
    ret
Leh_func_end1:

...
__Z6mulpowf:
Leh_func_begin2:
    pushq   %rbp
Ltmp2:
    movq    %rsp, %rbp
Ltmp3:
    mulss   %xmm0, %xmm0
    popq    %rbp
    ret

Upvotes: 6

Eric Postpischil
Eric Postpischil

Reputation: 222323

num*num will be at least as fast as pow(num, 2) on any non-perverse C/C++ implementation, because there is no implementation of pow without at least one floating-point multiplication or more time-consuming operation.

Upvotes: 10

Related Questions