Math Functions Performance
In a recent C# blog entry, it was pointed out that Pow uses a complex trig function and is thus a performance gotcha.
So, I decided to do some additional tests with standard mathematical functions. In each case, the argument is x=8.5 and the result measures the time it takes to compute the function and perform an assignment relative to a floating-point add operation plus assignment. Note: I haven't checked to see if the computation time is consistent across a range of values.
x+x 1.0 x*x 1.0 Abs(x) 5.6 Round(x) 10.8 Sqrt(x) 18.9 Sign(x) 36.2 Floor(x) 69.3 Cos(x) 73.6 Ceiling(x) 76.9 Round(x,2) 109.4 Sin(x) 112.6 Log(x) 134.6 Atan(x) 154.7 Asin(x) 169.6 Acos(x) 176.5 Exp(x) 178.8 Pow(x,2) 227.2 Log(x,2) 304.5
- Addition and multiplication performance was not distinguishable in this test, most likely because the relative overhead of the loop and the assignment operation was higher than in my earlier tests with the Decimal data type.
- Pow(x,2) was indeed a performance pig. It was slower than all the other library functions, except Log(x,2). What's more surprising is that the alternative x*x is as essentially as fast as an addition.
- Round(x) and Abs(x) are very fast, followed by the Sqrt(x) function.
- An important lesson--use the simplest function if possible. That extra argument is costly. Round, for example, with an extra argument to indicates decimal places is ten times slower even when the argument passed is the default value.
- Cos(x) computes its result in 65% of the time it takes Sin(x). Don't assume related functions have related times.
- If you know the y=Cos(x), you can obtain Sin(x) in a fraction of the time by calculating Sqrt(1-y*y). This yielded a time of 18.9 in my addition profiling calculations, the same time as the vanilla Sqrt(x) despite the extra operations.