I am initialising an array and then reversing it a number of times to see the performance.
I want to understand if I have written code which cannot be compared or is Rust really so bad that it is taking so much time?
Here is the build and timing process of Rust:
rustc main.rs
time ./main
This runs and goes on and on. Which is surprising
Rust
fn reverse(mylist: &mut Vec<u16>) {
let length = mylist.len();
let mid_length = length / 2;
for number in 0..mid_length {
let mut a = mylist[number];
let mut b = mylist[length - number - 1];
mylist[number] = b;
mylist[length - number - 1] = a;
}
}
fn main() {
let array_size = 100000;
let iterations = 100000;
let mut v = vec![0u16; array_size];
for _ in 0..iterations {
reverse(&mut v);
}
}
Go
The Go code does exactly what Rust code is doing above. The important thing to note is that Go has Garbage Collection where as Rust does not. Surprisingly, Go does the job in less than 6 seconds:
go build main.go
time ./main 100000 100000
real 0m5.932s
user 0m5.928s
sys 0m0.004s
Go
package main
import (
"os"
"strconv"
)
func reverse(mylist []int) []int {
length := len(mylist)
half := int(length / 2)
for i := 0; i < half; i++ {
mylist[i], mylist[length-i-1] = mylist[length-i-1], mylist[i]
}
return mylist
}
func main() {
array_size, _ := strconv.Atoi(os.Args[1])
iterations, _ := strconv.Atoi(os.Args[2])
mylist := make([]int, array_size)
for i := 0; i < iterations; i++ {
reverse(mylist)
}
}