Expand description
§Branches
branches
provides branch hinting prediction and control functions for optimization of algorithms, using built-in Rust features on stable and core::intrinsics
on nightly.
§Usage
To use branches
, add the following to your Cargo.toml
file:
[dependencies]
branches = "0.2"
For a no_std environment, disable the default features by adding the following to your Cargo.toml
instead:
[dependencies]
branches = { version = "0.2", default-features = false }
§Functions
The following functions are provided by branches
:
likely(b: bool) -> bool
: Returns the input value but provides hints for the compiler that the statement is likely to be true.unlikely(b: bool) -> bool
: Returns the input value but provides hints for the compiler that the statement is unlikely to be true.assume(b: bool)
: Assumes that the input condition is always true and causes undefined behavior if it is not. On stable Rust, this function usescore::hint::unreachable_unchecked()
to achieve the same effect.abort()
: Aborts the execution of the process immediately and without any cleanup.
Here’s an example of how you can use likely
to optimize a function:
use branches::likely;
pub fn factorial(n: usize) -> usize {
if likely(n > 1) {
n * factorial(n - 1)
} else {
1
}
}
By correctly using the functions provided by branches, you can achieve a 10-20% improvement in the performance of your algorithms.
§License
branches
is licensed under the MIT license. See the LICENSE
file for more information.
Functions§
- abort
- Aborts the execution of the process immediately and without any cleanup.
- assume⚠
- Informs the optimizer that a condition is always true.
- likely
- Hints to the compiler that the branch condition is likely to be true. Returns the value passed to it.
- prefetch_
read_ ⚠data - Prefetches data for reading into the cache.
- prefetch_
write_ ⚠data - Prefetches data for writing into the cache.
- unlikely
- Hints to the compiler that the branch condition is unlikely to be true. Returns the value passed to it.