Skip to content

Instantly share code, notes, and snippets.

@elderica
Created January 16, 2023 12:55
Show Gist options
  • Save elderica/134db0539e7ecaee202967c9af6d6725 to your computer and use it in GitHub Desktop.
Save elderica/134db0539e7ecaee202967c9af6d6725 to your computer and use it in GitHub Desktop.
struct XOR64 {
x: u64,
}
impl XOR64 {
fn new(seed: u64) -> Self {
Self {
x: seed ^ 88172645463325252,
}
}
fn next(&mut self) -> u64 {
let x = self.x;
let x = x ^ (x << 13);
let x = x ^ (x >> 7);
let x = x ^ (x << 17);
self.x = x;
x
}
}
const CORES: usize = 16;
const NUM: usize = 4000_0000;
fn randomized_vec() -> Vec<Vec<u64>> {
let mut generator = XOR64::new(1234);
let mut vs = Vec::new();
for _ in 0..CORES {
let mut v = Vec::with_capacity(NUM);
for _ in 0..NUM {
let x = generator.next();
v.push(x);
}
vs.push(v);
}
vs
}
fn single_threaded() {
let mut vs = randomized_vec();
let start = std::time::Instant::now();
vs.iter_mut().for_each(|v| v.sort());
let end = start.elapsed();
println!(
"single_threaded: {}.{:03}秒",
end.as_secs(),
end.subsec_nanos()
);
}
fn multi_threaded() {
let vs = randomized_vec();
let start = std::time::Instant::now();
let mut handlers = Vec::new();
for mut v in vs.into_iter() {
let handler = std::thread::spawn(move || {
v.sort();
v
});
handlers.push(handler);
}
for h in handlers.into_iter() {
h.join().unwrap();
}
let end = start.elapsed();
println!(
"multi_threaded: {}.{:03}秒",
end.as_secs(),
end.subsec_nanos()
);
}
fn main() {
single_threaded();
multi_threaded();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment