Skip to content

Instantly share code, notes, and snippets.

@etcwilde
Last active September 1, 2015 23:28
Show Gist options
  • Save etcwilde/866e203e576fa1cfd1b1 to your computer and use it in GitHub Desktop.
Save etcwilde/866e203e576fa1cfd1b1 to your computer and use it in GitHub Desktop.
Some quick and dirty Rust snippets
extern crate rand;
extern crate time;
use std::thread;
use std::sync::mpsc;
use rand::distributions::{IndependentSample, Range};
use time::PreciseTime;
/// Conncurent Monte-carlo PI calculator
fn main()
{
let start = PreciseTime::now();
// Message passing
let (tx, rx) = mpsc::channel();
// Number of points to test
let total = 100000000;
let threads = 8; let samples = total / threads;
let mut in_circle = 0;
for _ in 0 .. threads
{
let tx = tx.clone();
thread::spawn(move ||
{
let mut total: u32 = 0;
let between = Range::new(-1f64, 1.);
let mut rng = rand::thread_rng();
for _ in 0 .. samples
{
let a = between.ind_sample(&mut rng);
let b = between.ind_sample(&mut rng);
total += (a*a + b*b <= 1.) as u32;
}
match tx.send(total)
{
Ok(_) => 1,
Err(_) => panic!("Failed to send"),
};
});
}
for _ in 0 .. threads
{
let result = match rx.recv()
{
Ok(m) => m,
Err(e) => panic!("Something bad happend {}", e),
};
in_circle += result;
}
let end = PreciseTime::now();
println!("PI estimation: {}", 4. * (in_circle as f64) / (total as f64));
println!("Estimation Time: {}", start.to(end));
}
use std::env;
use std::process;
use std::fs::File;
use std::io::prelude::*;
// Takes filename as commandline argument
// Opens and outputs content of file
fn main()
{
let args: Vec<_> = env::args().collect();
if args.len() < 2
{
println!("Usage: {} <filename>", args[0]);
process::exit(0);
}
println!("Opening File: {}", args[1]);
let mut file =
match File::open(&args[1])
{
Ok(f) => f,
Err(e) => panic!("File Error: {}", e),
};
let mut s = String::new();
match file.read_to_string(&mut s)
{
Ok(_) => 0,
Err(e) => panic!("Failed to read file: {}", e),
};
print!("File Contents:\n\n{}", s);
}
extern crate rand;
extern crate time;
use rand::distributions::{IndependentSample, Range};
use time::PreciseTime;
/// Monte-carlo PI calculator
fn main()
{
let start = PreciseTime::now();
let between = Range::new(-1f64, 1.);
let mut rng = rand::thread_rng();
let total = 100000000;
let mut in_circle = 0;
for _ in 0 .. total
{
let a = between.ind_sample(&mut rng);
let b = between.ind_sample(&mut rng);
if a*a + b * b < 1. { in_circle += 1; }
}
let end = PreciseTime::now();
println!("PI estimation: {}", 4. * (in_circle as f64) / (total as f64));
println!("Estimation Time: {}", start.to(end));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment