Skip to content

Instantly share code, notes, and snippets.

@k0nserv
Last active March 19, 2024 11:19
Show Gist options
  • Save k0nserv/adad82de01d5cfd705c1b9ec95ee10a7 to your computer and use it in GitHub Desktop.
Save k0nserv/adad82de01d5cfd705c1b9ec95ee10a7 to your computer and use it in GitHub Desktop.
trheadz.rs
use std::hint::black_box;
use std::thread;
use clap::Parser;
/// Simple program to test spawning many threads
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
/// Number of threads to spawn
#[arg(short, long, default_value_t = 10_000)]
num_threads: u64,
/// Stack depth(in numer of stack frames) to generate for each thread
#[arg(short, long, default_value_t = 1000)]
stack_depth: u64,
}
fn main() {
let Args {
num_threads,
stack_depth,
} = Args::parse();
let handles = (0..num_threads).map(|_| thread::spawn(move || run_thread(stack_depth)));
let mut sum = 0;
for handle in handles {
let s = handle.join().expect("to join thread");
sum += s;
}
println!("Sum: {sum}");
}
fn run_thread(count_to: u64) -> u64 {
// Stop the optimizer
return black_box(count(black_box(0), black_box(count_to)));
}
#[inline(never)]
fn count(cur: u64, to: u64) -> u64 {
let a = black_box([1; 1_00]);
if cur >= to {
return to;
}
return cur + count(cur + 1 + a[40], to);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment