use super::client::CpuClient;
pub(crate) const PARALLEL_MIN_WORK: usize = 32 * 1024;
#[cfg_attr(not(feature = "rayon"), allow(dead_code))]
pub(crate) fn fft_work(rows: usize, n: usize) -> usize {
let stages = n.next_power_of_two().trailing_zeros().max(1) as usize;
rows.saturating_mul(n).saturating_mul(stages)
}
impl CpuClient {
#[inline]
#[cfg_attr(not(feature = "rayon"), allow(dead_code))]
pub(crate) fn parallel_worthwhile(&self, work: usize) -> bool {
work >= PARALLEL_MIN_WORK
}
#[cfg(feature = "rayon")]
pub(crate) fn install_parallelism_if<F, T>(&self, parallel: bool, f: F) -> T
where
F: FnOnce() -> T + Send,
T: Send,
{
if parallel {
self.install_parallelism(f)
} else {
f()
}
}
#[cfg(not(feature = "rayon"))]
pub(crate) fn install_parallelism_if<F, T>(&self, _parallel: bool, f: F) -> T
where
F: FnOnce() -> T,
{
f()
}
pub(crate) fn par_for_each<F>(&self, count: usize, work: usize, body: F)
where
F: Fn(usize) + Send + Sync,
{
#[cfg(feature = "rayon")]
if count > 1 && self.parallel_worthwhile(work) {
use rayon::prelude::*;
let min_len = self.rayon_min_len();
self.install_parallelism(|| {
(0..count)
.into_par_iter()
.with_min_len(min_len)
.for_each(&body);
});
return;
}
#[cfg(not(feature = "rayon"))]
let _ = work;
(0..count).for_each(body);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::runtime::cpu::CpuDevice;
use std::sync::Mutex;
#[test]
fn test_gate_threshold() {
let client = CpuClient::new(CpuDevice::new());
assert!(!client.parallel_worthwhile(PARALLEL_MIN_WORK - 1));
assert!(client.parallel_worthwhile(PARALLEL_MIN_WORK));
}
#[test]
fn test_par_for_each_visits_every_index_once() {
let client = CpuClient::new(CpuDevice::new());
for &work in &[1usize, PARALLEL_MIN_WORK] {
let seen = Mutex::new(vec![0u32; 37]);
client.par_for_each(37, work, |i| {
if let Ok(mut s) = seen.lock() {
s[i] += 1;
}
});
let seen = seen.into_inner().unwrap_or_default();
assert_eq!(seen, vec![1u32; 37], "work={work}");
}
}
#[test]
fn test_small_work_runs_in_order_on_caller() {
let client = CpuClient::new(CpuDevice::new());
let caller = std::thread::current().id();
let order = Mutex::new(Vec::new());
client.par_for_each(10, 1, |i| {
assert_eq!(std::thread::current().id(), caller);
if let Ok(mut o) = order.lock() {
o.push(i);
}
});
let order = order.into_inner().unwrap_or_default();
assert_eq!(order, (0..10).collect::<Vec<_>>());
}
}