Can we get a performance boost from using a const generic function in Rust? In this program we the 2 test() functions, and the first uses a const type.
use std::time::*;
fn test<const N: bool>(max: i32) -> i32 {
let mut result = 0;
for _ in 0..max {
for i in 0..max {
result += if N == true {
1
} else {
2
};
if max - 2 == i {
break;
}
}
}
result
}
fn test_no_generic(n: bool, max: i32) -> i32 {
let mut result = 0;
for _ in 0..max {
for i in 0..max {
result += if n == true {
1
} else {
2
};
if max - 2 == i {
break;
}
}
}
result
}
fn main() {
if let Ok(max) =
"100000".parse() {
// Ensure bool is not known at compile-time.
let is_true = max % 2 == 0;
let mut sum1 = 0;
let mut sum2 = 0;
// Version 1: use const generic function.
let t0 = Instant::now();
if is_true {
sum1 += test::<true>(max);
} else {
sum1 += test::<false>(max);
}
println!(
"{}", t0.elapsed().as_millis());
// Version 2: use non-generic function.
let t1 = Instant::now();
sum2 += test_no_generic(is_true, max);
println!(
"{}", t1.elapsed().as_millis());
println!(
"{} = {}", sum1, sum2);
}
}
118 ms (const)
782 ms
1409965408 = 1409965408