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
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
22
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 --release
💡 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!
Top comments (2)
thx for the post! there is a minor typo in "--release":
RUSTFLAGS="-C target-cpu=native" cargo build --release
You're awesome 👨🎤