Skip to content

Instantly share code, notes, and snippets.

Created August 17, 2015 10:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/7a1f9b21d05290f2ae68 to your computer and use it in GitHub Desktop.
Save anonymous/7a1f9b21d05290f2ae68 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
#![feature(test)]
extern crate test;
use test::Bencher;
use std::cmp;
fn init_vecs() -> (Vec<f64>, Vec<f64>) {
let mut v1 = vec![0.0f64; 259];
for (idx, e) in v1.iter_mut().enumerate() {
*e = idx as f64 / 1029.0 as f64;
}
let mut v2 = vec![0.0f64; 253];
for (idx, e) in v2.iter_mut().enumerate() {
*e = 1.0 - idx as f64 / 1023.0 as f64;
}
(v1, v2)
}
fn naive_dot_product(x: &[f64], y: &[f64]) -> f64 {
x.iter().zip(y.iter()).fold(0.0, |sum, (&ex, &ey)| sum + (ex * ey))
}
fn index_dot_product(x: &[f64], y: &[f64]) -> f64 {
let n = cmp::min(x.len(), y.len());
let (x, y) = (&x[..n], &y[..n]);
let mut sum = 0.0;
for i in 0..n {
sum += x[i] * y[i];
}
sum
}
fn unrolled_dot_product(x: &[f64], y: &[f64]) -> f64 {
let n = cmp::min(x.len(), y.len());
let (mut x, mut y) = (&x[..n], &y[..n]);
let mut sum = 0.0;
while x.len() >= 8 {
sum += x[0] * y[0] + x[1] * y[1] + x[2] * y[2] + x[3] * y[3]
+ x[4] * y[4] + x[5] * y[5] + x[6] * y[6] + x[7] * y[7];
x = &x[8..];
y = &y[8..];
}
x.iter().zip(y.iter()).fold(sum, |sum, (&ex, &ey)| sum + (ex * ey))
}
#[bench]
fn bench_naive(b: &mut Bencher) {
let (x, y) = init_vecs();
b.iter(|| naive_dot_product(&x, &y));
}
#[bench]
fn bench_index(b: &mut Bencher) {
let (x, y) = init_vecs();
b.iter(|| index_dot_product(&x, &y));
}
#[bench]
fn bench_unrolled(b: &mut Bencher) {
let (x, y) = init_vecs();
b.iter(|| unrolled_dot_product(&x, &y));
}
#[test]
fn same_answer() {
let (v1, v2) = init_vecs();
let naive = naive_dot_product(&v1, &v2);
let index = index_dot_product(&v1, &v2);
let unrolled = unrolled_dot_product(&v1, &v2);
assert!((naive - index).abs() < 1e-8);
assert!((naive - unrolled).abs() < 1e-8);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment