DEV Community

Cover image for Building optimized binaries with Rust
Axel Navarro for Cloud(x);

Posted on

Building optimized binaries with Rust

We can enable architecture-specific optimizations when we compile Rust apps directly in the target CPU, and check some configuration values in our PKGBUILD.

With this optimizations, we could increase the performance of our rust apps up to 2x times.

Checking the native optimizations

We can check the default optimizations for the current CPU architecture:

$ rustc --print cfg

We can count only 3 target_feature values.

🧠 SSE is an instruction set for the x86 architecture created by Intel in 1999. 👀

We can see the available optimizations for our CPU using:

rustc -C target-cpu=native --print cfg

I can count the number of features (target_feature) that my CPU supports by using:

$ rustc -C target-cpu=native --print cfg | grep target_feature | wc -l

There are 19 additional optimizations than the default profile for my CPU architecture.

How to compile with native optimizations

The default scenario is to build in release mode using:

cargo build --release

To apply the native optimizations, you can use:

cargo rustc --release -- -C target-cpu=native

Or, with an environment variable:

RUSTFLAGS="-C target-cpu=native" cargo build --relase

💡 Remember: the environment variable this will apply the native compilation to all dependencies and not just the top crate.

Using makepkg with native optimizations

To apply these architecture-specific optimizations in Arch Linux you should edit the /etc/makepkg.conf adding -C target-cpu=native to the RUSTFLAGS variable.

💡 Note: If you want to distribute your package in different architectures remember to check the compatibility.

Finding your best optimization

Maybe target-cpu=native is not good enough for your needs. You can check the available options for your CPU using:

$ rustc --print target-cpus

Then, you could test different options for your CPU architecture. Good luck!

Discussion (0)