Skip to content

Commit ba2dbb7

Browse files
conradludgateibraheemdev
authored andcommitted
cache available_parallelism
1 parent 4f40c71 commit ba2dbb7

1 file changed

Lines changed: 11 additions & 4 deletions

File tree

src/raw/utils/counter.rs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
use std::sync::atomic::{AtomicIsize, Ordering};
1+
use std::sync::{
2+
atomic::{AtomicIsize, Ordering},
3+
OnceLock,
4+
};
25

36
use super::CachePadded;
47

@@ -14,9 +17,13 @@ pub struct Counter(Box<[CachePadded<AtomicIsize>]>);
1417
impl Default for Counter {
1518
/// Create a new `Counter`.
1619
fn default() -> Counter {
17-
let num_cpus = std::thread::available_parallelism()
18-
.map(usize::from)
19-
.unwrap_or(1);
20+
// available_parallelism is quite slow (microseconds).
21+
static CPUS: OnceLock<usize> = OnceLock::new();
22+
let num_cpus = *CPUS.get_or_init(|| {
23+
std::thread::available_parallelism()
24+
.map(Into::into)
25+
.unwrap_or(1)
26+
});
2027

2128
// Round up to the next power-of-two for fast modulo.
2229
let shards = (0..num_cpus.next_power_of_two())

0 commit comments

Comments
 (0)