Rust program has only 42% the speed of similar c++ program

Another thing you can do to go for maximum performance on the resulting binary is placing the following release profile in your cargo.toml:

[profile.release]
opt-level = 3 # Sets optimizing level to maximum performance with no regard for binary size
codegen-units = 1 # Instead of spreading code generation over multiple units only use one unit which can lead to better performance at the cost of compilation time
debug = false # No debug symbols
debug-assertions = false
lto = "fat" # Link time optimizations across all dependencies at the cost of higher compilation time
rpath = false
panic = "abort"

Combining this with the following command to compile always provides me with the highest performance I can get from my applications:

RUSTFLAGS="-Ctarget-cpu=native" cargo build --release --target=<your_target_triple i.e. x86_64_unknown-linux-gnu>

Though I can only advice you to play around with these settings and their values to find the optimum for your case.

Thank you!

Although this library only seems to generate unsigned integers.

You can enable the rand-traits feature for the types to implement RngCore, then use Rng::gen() to extract arbitrary integers.

2 Likes

The first is that when passing references to a Vec it is idiomatic to use &[f64] target than & Vec<f64> . The former is both more efficient (by a negligible amount) and more flexible.

In my first proper Rust program (which was a rewrite of C# and Python versions) I initially passed &Vec, as my goal was initially just to get a correctly working program. But I remembered seeing the idiomatic &[].

When I substituted that on my second pass I had a significant performance speedup. The timing went from 0.36s to 0.28s.

6 Likes

Thank you, but I must confess I do not really understand how I would do this. Could you please provide a small example snippet?

The traits are designed to be very simple to use.

/* in Cargo.toml:
[dependencies]
rand = "0.8.5"
rand_mt = "4.1.1"
*/

use rand::{Rng, SeedableRng};
use rand_mt::Mt64;

fn main() {
    let mut rng = Mt64::from_entropy();
    for _ in 0..10 {
        println!("{}", rng.gen_range(-1.0..=1.0));
    }
}

(Alternatively, any of the other Rng methods can be used to generate values.)

3 Likes