Skip to content

Instantly share code, notes, and snippets.

@am0d
Last active December 17, 2015 17:39
Show Gist options
  • Select an option

  • Save am0d/5647807 to your computer and use it in GitHub Desktop.

Select an option

Save am0d/5647807 to your computer and use it in GitHub Desktop.
Rust's vec::swap implementation is really slow ...
/* Sample bubble sort program in Rust.
Tested to compile with rust-0.6.
*/
extern mod std;
extern mod benchmark;
use benchmark::Benchmark;
#[cfg(std_swap)]
fn swap(arr: &mut [uint], left: uint, right: uint) {
use core::vec;
vec::swap(arr, left, right);
}
#[cfg(not(std_swap))]
fn swap(arr: &mut [uint], left: uint, right: uint) {
let tmp = arr[left];
arr[left] = arr[right];
arr[right] = tmp;
}
fn bubble_sort(arr: &mut [uint]) -> () {
let mut left: uint;
let mut right: uint = arr.len() - 1;
let mut swap_occurred = true;
while swap_occurred {
swap_occurred = false;
left = 0;
while left < right {
if arr[left+1] < arr[left] {
// swap the two values
swap(arr, left, left+1);
swap_occurred = true;
}
left += 1;
}
right -= 1;
}
return;
}
fn main() {
let mut bench = Benchmark::new();
bench.run(bubble_sort);
}
a_m0d@laptop ~/workspace/rust/projects/data-structures $ rustc timer.rs
a_m0d@laptop ~/workspace/rust/projects/data-structures $ rustc benchmark.rs -L .
a_m0d@laptop ~/workspace/rust/projects/data-structures $ rustc bubble-sort.rs -L .
a_m0d@laptop ~/workspace/rust/projects/data-structures $ ./bubble-sort --trialsize 10000 --numtrials 20 -qq
Average time: 874,499,663 ns
a_m0d@laptop ~/workspace/rust/projects/data-structures $ rustc bubble-sort.rs -L . --cfg std_swap
a_m0d@laptop ~/workspace/rust/projects/data-structures $ ./bubble-sort --trialsize 10000 --numtrials 20 -qq
Average time: 5.289 sec
a_m0d@laptop ~/workspace/rust/projects/data-structures $ rustc bubble-sort.rs -L . -O
a_m0d@laptop ~/workspace/rust/projects/data-structures $ ./bubble-sort --trialsize 10000 --numtrials 20 -qq
Average time: 159,953,131 ns
a_m0d@laptop ~/workspace/rust/projects/data-structures $ rustc bubble-sort.rs -L . -O --cfg std_swap
a_m0d@laptop ~/workspace/rust/projects/data-structures $ ./bubble-sort --trialsize 10000 --numtrials 20 -qq
Average time: 159,677,076 ns
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment