Hi everyone, I am a beginner at Rust lang.
Because I heard that Rust has better performance than other languages with garbage collection, I tried to rewrite a tiny Python tool with Rust as a practice.
In this tool, there is a simple function, which multiplies each element in two lists one by one and records the maximum result. The python code is shown below:
import time
from numba import njit
@njit
def findMax(a,b):
print(len(a),len(b))
maxone=0
for i in a:
for j in b:
if i*j>maxone:
maxone=i*j
return maxone
a=[0.5 for i in range(20000)]
b=[0.4 for j in range(20000)]
t0=time.time()
s=findMax(a,b)
t1=time.time()
print(str(t1-t0)+"s res:"+str(s))
As you can see, I use Numba to pre-compile this function into LLVM codes to accelerate it. The running result is:
0.7270545959472656s res:0.2
Without Numba pre-compile, its result is:
16.186195135116577s res:0.2
You can see that the Python with Numba is 20 times faster than the original Python code.
I learnt that Rust lang also compiles its code into LLVM codes, so I think this function should run faster with Rust codes:
use std::time::{SystemTime, UNIX_EPOCH};
fn simple_mul(va:Vec<f64>, vb:Vec<f64>) ->f64{
println!("{},{}",va.len(),vb.len());
let mut maxone=0.0;
for i in va.iter(){
for j in vb.iter(){
if i*j>maxone{
maxone=i*j;
}
}
}
return maxone;
}
fn main() {
let va=vec![0.5;20000];
let vb=vec![0.4;20000];
let t0=SystemTime::now().duration_since(UNIX_EPOCH)
.expect("Time went backwards");
let res= simple_mul(va, vb);
let t1=SystemTime::now().duration_since(UNIX_EPOCH)
.expect("Time went backwards");
print!("{}s,ans {}",t1.as_secs_f64()-t0.as_secs_f64(),res);
}
But the testing result is:
8.995279312133789s,ans 0.2
This result confuses me: the function written in Rust is ten times slower than Python with Numba, and there is not apparent speed advantage of Rust code over the original Python code, either.
I tried to fill the testing lists(vectors) with random numbers(use rand crate) in the testing, or use arrays instead of vectors in Rust, but the result kept the same.
Is there any mistake with my Rust code? Thanks for the help!