#branch #optimization #likely #unlikely

no-std branches

Branch hinting prediction and control functions for stable Rust including likely, unlikely, assume and abort to help algorithm optimization

4 releases

0.1.3 May 17, 2023
0.1.2 Mar 25, 2023
0.1.1 Mar 9, 2023
0.1.0 Mar 4, 2023

#89 in No standard library

Download history 256/week @ 2023-11-20 176/week @ 2023-11-27 181/week @ 2023-12-04 173/week @ 2023-12-11 214/week @ 2023-12-18 248/week @ 2023-12-25 128/week @ 2024-01-01 299/week @ 2024-01-08 166/week @ 2024-01-15 110/week @ 2024-01-22 87/week @ 2024-01-29 96/week @ 2024-02-05 70/week @ 2024-02-12 135/week @ 2024-02-19 216/week @ 2024-02-26 171/week @ 2024-03-04

595 downloads per month
Used in 17 crates (3 directly)

MIT license

7KB

Branches

Crates.io Documentation MIT licensed

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.1"

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 uses core::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.

No runtime deps