From 8a14a408a5355c925f178ece715fa176ef14b6b5 Mon Sep 17 00:00:00 2001 From: Acrimon Date: Tue, 4 Aug 2020 19:52:14 +0200 Subject: [PATCH] fix: #100 --- Cargo.toml | 1 + src/lib.rs | 18 ++++++++++++------ 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 657491a..5d693e5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,7 @@ raw-api = [] no_std = ["hashbrown"] [dependencies] +num_cpus = "1.13.0" ahash = "0.3.8" serde = { version = "1.0.114", optional = true, features = ["derive"] } cfg-if = "0.1.10" diff --git a/src/lib.rs b/src/lib.rs index b832e29..0222dd9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -49,8 +49,13 @@ cfg_if! { } } -const SHARD_AMOUNT: usize = 8; -const NCB: usize = SHARD_AMOUNT.trailing_zeros() as usize; +fn shard_amount() -> usize { + (num_cpus::get() * 4).next_power_of_two() +} + +fn ncb(shard_amount: usize) -> usize { + shard_amount.trailing_zeros() as usize +} /// DashMap is an implementation of a concurrent associative array/hashmap in Rust. /// @@ -167,15 +172,16 @@ impl<'a, K: 'a + Eq + Hash, V: 'a, S: BuildHasher + Clone> DashMap { /// ``` pub fn with_capacity_and_hasher(mut capacity: usize, hasher: S) -> Self { - let shift = util::ptr_size_bits() - NCB; + let shard_amount = shard_amount(); + let shift = util::ptr_size_bits() - ncb(shard_amount); if capacity != 0 { - capacity = (capacity + (SHARD_AMOUNT - 1)) & !(SHARD_AMOUNT - 1); + capacity = (capacity + (shard_amount - 1)) & !(shard_amount - 1); } - let cps = capacity / SHARD_AMOUNT; + let cps = capacity / shard_amount; - let shards = (0..SHARD_AMOUNT) + let shards = (0..shard_amount) .map(|_| RwLock::new(HashMap::with_capacity_and_hasher(cps, hasher.clone()))) .collect();