public snapshot · system/tools/nib/bench/xlang/ · system@main · commit a92f56ab098e · shared 2026-11-22T22:43:57Z· frozen: this page does not change when the repository does
all files
  1// mandelbrot on every core: mandelbrot.rs's image and output, one scoped
  2// thread per available core, each taking the next row from a shared counter.
  3use std::sync::atomic::{AtomicUsize, Ordering};
  4use std::thread;
  5
  6fn row(y: usize, size: usize, iters: usize) -> (u64, u64) {
  7    let ci = 2.0 * y as f64 / size as f64 - 1.0;
  8    let mut bytes = vec![0u8; (size + 7) / 8];
  9    let mut count = 0u64;
 10    for x in 0..size {
 11        let cr = 2.0 * x as f64 / size as f64 - 1.5;
 12        let (mut zr, mut zi) = (0.0f64, 0.0f64);
 13        let mut inside = true;
 14        for _ in 0..iters {
 15            let t = zr * zr - zi * zi + cr;
 16            zi = 2.0 * zr * zi + ci;
 17            zr = t;
 18            if zr * zr + zi * zi > 4.0 {
 19                inside = false;
 20                break;
 21            }
 22        }
 23        if inside {
 24            bytes[x / 8] |= 0x80 >> (x % 8);
 25            count += 1;
 26        }
 27    }
 28    (bytes.iter().map(|&b| b as u64).sum(), count)
 29}
 30
 31fn main() {
 32    let size = 4000usize;
 33    let iters = 50;
 34    let threads = thread::available_parallelism()
 35        .map(|n| n.get())
 36        .unwrap_or(1);
 37    let next = AtomicUsize::new(0);
 38    let (byte_sum, count) = thread::scope(|s| {
 39        let handles: Vec<_> = (0..threads)
 40            .map(|_| {
 41                s.spawn(|| {
 42                    let mut acc = (0u64, 0u64);
 43                    loop {
 44                        let y = next.fetch_add(1, Ordering::Relaxed);
 45                        if y >= size {
 46                            break acc;
 47                        }
 48                        let (b, c) = row(y, size, iters);
 49                        acc.0 += b;
 50                        acc.1 += c;
 51                    }
 52                })
 53            })
 54            .collect();
 55        handles
 56            .into_iter()
 57            .map(|h| h.join().unwrap())
 58            .fold((0, 0), |a, b| (a.0 + b.0, a.1 + b.1))
 59    });
 60    println!("{}\n{}", byte_sum, count);
 61}