Finish powf post.
This commit is contained in:
1 parent
5a6717ad3a
commit
4ce9eb3fd1
3 files changed
+48
-81
No files matched your search
@@ -0,0 +1,48 @@
|
||||
---
|
||||
title: "Rust: powf is slow"
|
||||
author: "James Pace"
|
||||
date: "2024/01/31"
|
||||
---
|
||||
|
||||
I'm currently working on a project in Rust which does a lot of math on
|
||||
a microcontroller.
|
||||
In Rust, normal math operations (like absolute value and square
|
||||
root for floats) are provided as part of the standard library (called `std`),
|
||||
which is not available for the microcontroller I'm using.
|
||||
Thus, alternate libraries have to be used.
|
||||
|
||||
The two major ones I've found (and which I need to do a detailed comparison
|
||||
of) are [micromath][micromath] and [libm][libm].
|
||||
For now, I've been using `libm`, mainly because its the first one I found.
|
||||
|
||||
One of the operations my project does a lot is find the distance between two points.
|
||||
My initial implementation did something like
|
||||
```rust
|
||||
fn distance(point1: &Point, point2: &Point) -> f32 {
|
||||
let squared_dist = libm::powf((point2.x - point1.x), 2.0) + libm::powf((point2.y - point1.y), 2.0);
|
||||
sqrt(squared_dist)
|
||||
}
|
||||
```
|
||||
|
||||
While doing some profiling, I switched to
|
||||
```rust
|
||||
fn distance(point1: &Point, point2: &Point) -> f32 {
|
||||
let x_dist = point2.x - point1.x;
|
||||
let y_dist = point2.y - point1.y;
|
||||
|
||||
let squared_dist = x_dist*x_dist + y_dist*y_dist;
|
||||
libm::sqrt(squared_dist)
|
||||
}
|
||||
```
|
||||
which was significantly faster, especially on the `microbit` I was running the code on for
|
||||
profiling.
|
||||
|
||||
Out of curiousity, I tried doing the same thing, but on my laptop using `std::powf` instead
|
||||
of `libm::powf`.
|
||||
|
||||
When compiling with the default optimization level (`-O3`), I saw a similar performance
|
||||
increase, but not when I switched to compiling with `--release`, which I found interesting,
|
||||
and which underscores the importance of building in `--release` which shipping Rust binaries.
|
||||
|
||||
[libm]: https://github.com/rust-lang/libm
|
||||
[micromath]: https://github.com/tarcieri/micromath
|
||||
Reference in new issue
Block a user