Last active
August 29, 2015 14:11
-
-
Save benwilson512/f28567024e2ef932f9af to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![feature(simd)] | |
#![allow(experimental)] | |
extern crate test; | |
extern crate time; | |
use std::simd::f64x2; | |
use std::sync::{Arc,Future}; | |
static CHUNKS: uint = 4; | |
static POINTS: uint = 10000000; | |
static CHUNK_SIZE: uint = 10000000 / 8; | |
fn main() { | |
let points = Vec::from_fn(POINTS, |i| f64x2(i as f64, i as f64)); | |
let start = time::precise_time_ns(); | |
linear_regression(points); | |
let end = time::precise_time_ns(); | |
println!("{}ms", (end-start) as f64/1000000.0); | |
} | |
fn linear_regression(points: Vec<f64x2>) -> (f64, f64) { | |
let shared_points = Arc::new(points); | |
let tasks = Vec::from_fn(CHUNKS, |i| { | |
let local_points = shared_points.clone(); | |
let task = Future::spawn(proc() { | |
sum_parts(local_points.slice(i*CHUNK_SIZE, (i + 1) * CHUNK_SIZE)) | |
}); | |
task | |
}); | |
let mut products_avg = 0f64; | |
let mut x_sqr_avg = 0f64; | |
let mut x_avg = 0f64; | |
let mut y_avg = 0f64; | |
for mut res in tasks.into_iter() { | |
let (products_avg1, x_sqr_avg1, x_avg1, y_avg1) = res.get(); | |
products_avg = products_avg + products_avg1; | |
x_sqr_avg = x_sqr_avg + x_sqr_avg1; | |
x_avg = x_avg + x_avg1; | |
y_avg = y_avg + y_avg1; | |
} | |
let slope = (products_avg - x_avg * y_avg) / (x_sqr_avg - x_avg * y_avg); | |
let intercept = y_avg - slope * x_avg; | |
return (slope, intercept) | |
} | |
fn sum_parts(points: &[f64x2]) -> (f64, f64, f64, f64) { | |
let mut products_avg = 0f64; | |
let mut x_sqr_avg = 0f64; | |
let mut x_y_avgs = f64x2(0f64, 0f64); | |
for point in points.iter() { | |
let f64x2(x, y) = *point; | |
products_avg += x * y; | |
x_sqr_avg += x * x; | |
x_y_avgs += *point; | |
} | |
let num_points = points.len() as f64; | |
products_avg = products_avg / num_points; | |
x_sqr_avg = x_sqr_avg / num_points; | |
let f64x2(x_avg, y_avg) = x_y_avgs / f64x2(num_points, num_points); | |
(products_avg, x_sqr_avg, x_avg, y_avg) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment