Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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



As 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.


It certainly does do this: 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.


Interesting, thank you!

I suspect then that defining it at x*x is just just because it's easier to type than x.powi(2).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: