Skip to content

Instantly share code, notes, and snippets.

@AlexCMueller
Created February 1, 2021 15:05
Show Gist options
  • Save AlexCMueller/a788107f305f7ded8b25378d059ba663 to your computer and use it in GitHub Desktop.
Save AlexCMueller/a788107f305f7ded8b25378d059ba663 to your computer and use it in GitHub Desktop.
rust monte carlo
# omitted most of file
futures = "0.3.12"
rand = { version = "0.8.3", features = ["small_rng"] }
switchyard = "0.1.1"
use std::cell::RefCell;
use std::time::Instant;
use futures::executor::block_on;
use rand::prelude::*;
use switchyard::Switchyard;
use switchyard::threads::{thread_info, single_pool_one_to_one};
struct ThreadLocalData {
rng: SmallRng,
count: u64,
}
impl ThreadLocalData {
fn new() -> ThreadLocalData {
ThreadLocalData {
rng: SmallRng::from_entropy(),
count: 0,
}
}
}
fn main() {
let start = Instant::now();
let mut yard = Switchyard::new(
1,
single_pool_one_to_one(thread_info(), None),
|| RefCell::new(ThreadLocalData::new()),
).unwrap();
const N_JOBS: u64 = 100_000;
const N_ITERS_PER_JOB: u64 = 10_000;
for _ in 0..N_JOBS {
yard.spawn_local(0, 0, |data| async move {
let mut borrowed_data = data.borrow_mut();
let mut local_count = 0;
for _ in 0..N_ITERS_PER_JOB {
let (x, y) = borrowed_data.rng.gen::<(f32, f32)>();
if x*x + y*y <= 1.0 {
local_count += 1;
}
}
borrowed_data.count += local_count;
});
}
block_on(yard.wait_for_idle());
let total_hits = yard.access_per_thread_data()
.unwrap()
.iter()
.map(|d| d.borrow_mut().count)
.sum::<u64>();
println!("{}", 4.0 * total_hits as f64 / (N_JOBS * N_ITERS_PER_JOB) as f64);
yard.finish();
println!("{}", start.elapsed().as_secs_f64());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment