Quick Rust Comparison

I've been wanting to try out Rust with something very simple as a first pass through the language.

Rust Impressions

Although I didn't do much with functions on this quick pass - I love the ability to not have the order of main in a program to matter.

Super helpful error messages. Here is an example:

warning: value assigned to `temp` is never read
 --> src/main.rs:4:13
  |
4 |     let mut temp=0u32;
  |             ^^^^
  |
  = note: `#[warn(unused_assignments)]` on by default
  = help: maybe it is overwritten before being read?

I know others have said this, but the Rust compiler feels like it was designed to help me code, rather than just throw errors.

Speed?

I decided to write a simple unoptimized version of the fibonacci sequence. My goal was to take enough time to be noticable...

On my first pass:
  • Rust runs took 1m34seconds (using cargo run)
  • Python took more than 6 minutes
  • C got 7 seconds

Clearly I must have done something wrong...

It turns out that by default it has debug info and checks that slow Rust down. So a

cargo build --release
./target/release/fib

Then it was faster than C.. and I realized I need to turn off C\'s debug bits too with:

gcc -O2 -s -DNDEBUG to gcc helped. gcc  fib.c
The final results (all approximate):
  • Python: 6+ minutes.
  • C: 1.101s
  • Rust: .95sE

The Rust

fn main() {
    let mut previous=0u32;
    let mut current=1u32;
    let mut temp;
    let maxvalue = 2000000000u32;

    for _n in 0..2000000000 {
            if current >= maxvalue {
                //Reset!
                previous=0; current=1;
            }
        temp = current;
        current = previous + current;
        previous = temp;
    }
    println!("{}", current);
}

The C

#include <stdio.h>
int main() {

    unsigned long int previous=0;
    unsigned long int current=1;
    unsigned long int temp;
    unsigned long int maxvalue = 2000000000;
    for ( int n=0; n < 2000000000; n++ ) {
        if (current >= maxvalue) {
                //Reset!
                previous=0; current=1;
        }
        temp = current;
        current = previous + current;
        previous = temp;
    }
    printf("%lu", current);
}

The Python3

previous=0;
current=1;
temp = 0;
maxvalue = 2000000000;

for n in range(2000000000):
    if current >= maxvalue:
        #Reset!
        previous=0; current=1;
    temp = current;
    current = previous + current;
    previous = temp;
print(current);