Oct 10, 2011

Math.Pow(x,2) vs x * x

I've recently commented on posts on gamedev.net where the author posted some code they were concerned about the speed of. In each example I noted they were using the Math.Pow() function to calculate the square of a number.

In each circumstance I recommended they alter their code to multiply the two values together. This was mostly based on the "gut feel" that Math.Pow() should be slower. That's fairly poor practise, and because I loathe giving people a bum steer, I decided I should do a quick benchmark on my CPU.

100 million iterations in a tight loop. (x is a double):

Math.Pow(x,2)8.540 seconds
x * x1.152 seconds

Similarly, as an aside, Math.Sqrt(x) is significantly faster than Math.Pow(x,0.5):

Math.Pow(x,0.5)8.543 seconds
Math.Sqrt(x)1.737 seconds

The results are pretty clear. Stay away from Math.Pow(x,2) and Math.Pow(x,0.5). I did some further benchmarking on higher integer powers, and Math.Pow() stays the same, while x * x * x ... gets slower as you'd expect. The breakeven point is somewhere around x ^ 20 I think. So it's still better to do the direct multiplication for x ^ 3 and x ^ 4.

I was actually surprised by the performance of Math.Sqrt(x), I thought it would be alot slower than it turned out to be. The important lesson here is to always benchmark.

1 comment:

Note: Only a member of this blog may post a comment.