4 ms·
For your `sqr` function, what is the benefit of writing `x * x` over using `x.powi(2)` [0]? You didn't mention it in the article, but did you find a performance
by JoshMcguigan 7y ago
For your `sqr` function, what is the benefit of writing `x * x` over using `x.powi(2)` [0]? You didn't mention it in the article, but did you find a performance improvement from doing this?
[0]: https://doc.rust-lang.org/std/primitive.f64.html#method.powi https://doc.rust-lang.org/std/primitive.f64.html#method.powi
- chias 7y agoAs far as CPU instructions go, multiplication is _significantly_ faster (i.e. an order of magnitude) than exponentiation. That said, I can't speak to whether the Rust compiler wouldn't just optimize that away -- it seems like unrolling exponentiation into multiplication for small constant powers would be a very safe and easy thing to do.
- raphlinus 7y agoIt certainly does do this: https://rust.godbolt.org/z/ZaDAKa https://rust.godbolt.org/z/ZaDAKa Not just small constant powers either. I tried .powi(1000000) and it compiled into a sequence of 25 vmulss instructions.
- chias 7y agoInteresting, thank you! I suspect then that defining it at x*x is just just because it's easier to type than x.powi(2).