RUST code optimisation
Hi, I'm beginning with RUST, and I was comparing some code written in C# to see if it performs well. I find that the RUST version is slower, but I don't know if I made some obvious mistakes. I tried unsuccessfully some optimisation (like use iterators instead of the for loop).
Any advice to speed up the RUST version without multithreading?
C# → 20 sec :
var random = new Random();
const int count = 4096;
double[] data = (from i in Enumerable.Range(0,count) select (double)random.NextDouble()).ToArray();
var watch = new System.Diagnostics.Stopwatch();
watch.Start();
double[] output = new double[count];
for(int id = 0;id < count;id++) {
double value = data[id];
for(int i = 0;i < 3000000;i++) {
if(value > 0.5) {
value *= 0.99;
} else {
value *= 1.01;
}
}
output[id] = value;
}
watch.Stop();
Console.WriteLine($"Execution Time: {watch.Elapsed.TotalSeconds} sec");
Console.WriteLine($"{output[23]}");
RUST → 41 seconds
use std::time::Instant;
use rand::Rng;
const COUNT: usize = 4096;
fn main() {
let mut data = vec![0.0f32; COUNT];
let mut output = vec![0.0f32; data.len()];
let mut rng = rand::thread_rng();
for val in data.iter_mut() {
*val = rng.gen();
}
let now = Instant::now();
output.iter_mut().zip(data).for_each(
|(value, input)|
{
*value = input;
(0..3000000).into_iter().for_each(|_|
if *value > 0.5f32 {
*value *= 0.99f32;
} else {
*value *= 1.01f32;
}
);
}
);
let elapsed = now.elapsed();
println!("Elapsed: {} seconds", elapsed.as_secs());
println!("{}", output[23]);
}