What of these two methods is in C more efficient? And how about:
pow(x,3)
vs.
x*x*x // etc?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
UPDATE 2021
I’ve modified the benchmark code as follows:
<random>used instead ofrand()I get the following results with GCC 10 -O2 (in seconds):
GCC 10 -O3 is almost identical to GCC 10 -O2.
With GCC 10 -O2 -ffast-math:
With GCC 10 -O3 -ffast-math:
With Clang 12 -O2:
Clang 12 -O3 is almost identical to Clang 12 -O2.
With Clang 12 -O2 -ffast-math:
Clang 12 -O3 -ffast-math is almost identical to Clang 12 -O2 -ffast-math.
Machine is Intel Core i7-7700K on Linux 5.4.0-73-generic x86_64.
Conclusions:
x*x*x...is always fasterstd::powis as fast asx*x*x...for odd exponentsstd::powis as fast asx*x*x...for all test cases, and is around twice as fast as -O2.pow(double, double)is always much slowerx*x*x...is faster for exponents greater than 2pow(double, double)is as fast asstd::powfor integral exponentsI’ll eventually get around to installing a more recent version of GCC on my machine and will update my results when I do so.
Here’s the updated benchmark code:
Old Answer, 2010
I tested the performance difference between
x*x*...vspow(x,i)for smalliusing this code:Results are:
Note that I accumulate the result of every pow calculation to make sure the compiler doesn’t optimize it away.
If I use the
std::pow(double, double)version, andloops = 1000000l, I get:This is on an Intel Core Duo running Ubuntu 9.10 64bit. Compiled using gcc 4.4.1 with -o2 optimization.
So in C, yes
x*x*xwill be faster thanpow(x, 3), because there is nopow(double, int)overload. In C++, it will be the roughly same. (Assuming the methodology in my testing is correct.)This is in response to the comment made by An Markm:
Even if a
using namespace stddirective was issued, if the second parameter topowis anint, then thestd::pow(double, int)overload from<cmath>will be called instead of::pow(double, double)from<math.h>.This test code confirms that behavior: