Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.Pow vs multiply operator (performance)

Anyone knows if multiply operator is faster than using the Math.Pow method? Like:

n * n * n 

vs

Math.Pow ( n, 3 ) 
like image 229
Joan Venge Avatar asked Jun 01 '09 20:06

Joan Venge


People also ask

Is POW faster than multiplication C++?

C++11 Performance Tip: Update on When to Use std::pow When not compiling with -ffast-math, direct multiplication was significantly faster than std::pow , around two orders of magnitude faster when comparing x * x * x and code:std::pow(x, 3) .

Is Math POW inefficient?

Math. pow is slow because it deals with an equation in the generic sense, using fractional powers to raise it to the given power. It's the lookup it has to go through when computing that takes more time. Simply multiplying numbers together is often faster, since native calls in Java are much more efficient.

Is POW function slow?

x^2 using pow() is therefore slower than x*x . Many modern compilers will in fact optimize out pow with constant integer arguments, but this should not be relied upon.


1 Answers

I just reinstalled windows so visual studio is not installed and the code is ugly

using System; using System.Diagnostics;  public static class test{  public static void Main(string[] args){     MyTest();     PowTest(); }  static void PowTest(){     var sw = Stopwatch.StartNew();     double res = 0;     for (int i = 0; i < 333333333; i++){         res = Math.Pow(i,30); //pow(i,30)     }     Console.WriteLine("Math.Pow: " + sw.ElapsedMilliseconds + " ms:  " + res); }  static void MyTest(){     var sw = Stopwatch.StartNew();     double res = 0;     for (int i = 0; i < 333333333; i++){         res = MyPow(i,30);     }     Console.WriteLine("MyPow: " + sw.ElapsedMilliseconds + " ms:  " + res); }    static double MyPow(double num, int exp) {     double result = 1.0;     while (exp > 0)     {         if (exp % 2 == 1)             result *= num;         exp >>= 1;         num *= num;     }      return result; } } 

The results:
csc /o test.cs

test.exe

MyPow: 6224 ms:  4.8569351667866E+255   Math.Pow: 43350 ms:  4.8569351667866E+255  

Exponentiation by squaring (see https://stackoverflow.com/questions/101439/the-most-efficient-way-to-implement-an-integer-based-power-function-powint-int) is much faster than Math.Pow in my test (my CPU is a Pentium T3200 at 2 Ghz)

EDIT: .NET version is 3.5 SP1, OS is Vista SP1 and power plan is high performance.

like image 111
ggf31416 Avatar answered Oct 02 '22 11:10

ggf31416