DEV Community

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

Posted on • Updated 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
debug_assertions
target_arch="x86_64"
target_endian="little"
target_env="gnu"
target_family="unix"
target_feature="fxsr"
target_feature="sse"
target_feature="sse2"
target_os="linux"
target_pointer_width="64"
target_vendor="unknown"
unix
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
22
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

To apply the native optimizations, you can use:

cargo rustc --release -- -C target-cpu=native
Enter fullscreen mode Exit fullscreen mode

Or, with an environment variable:

RUSTFLAGS="-C target-cpu=native" cargo build --release
Enter fullscreen mode Exit fullscreen mode

💡 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
Enter fullscreen mode Exit fullscreen mode

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

Top comments (2)

Collapse
 
nyurik profile image
Yuri Astrakhan

thx for the post! there is a minor typo in "--release":

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

Collapse
 
navarroaxel profile image
Axel Navarro

You're awesome 👨‍🎤