1use rayon::ThreadPoolBuilder;
2use std::fmt;
3
4#[derive(Debug, Clone)]
6pub struct SystemProfile {
7 pub logical_cpus: usize,
8 pub physical_cpus: Option<usize>,
9 pub total_memory_mb: u64,
10 pub available_memory_mb: u64,
11 pub worker_threads: usize,
12 pub progress_interval: u64,
13 pub memory_pressure: MemoryPressure,
14 pub measured_keys_per_sec: Option<f64>,
16}
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum MemoryPressure {
20 Comfortable,
21 Moderate,
22 Low,
23}
24
25impl fmt::Display for MemoryPressure {
26 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27 match self {
28 MemoryPressure::Comfortable => write!(f, "comfortable"),
29 MemoryPressure::Moderate => write!(f, "moderate"),
30 MemoryPressure::Low => write!(f, "low"),
31 }
32 }
33}
34
35impl SystemProfile {
36 pub fn detect() -> Self {
38 let logical_cpus = std::thread::available_parallelism()
39 .map(|n| n.get())
40 .unwrap_or(1);
41
42 let (physical_cpus, total_memory_mb, available_memory_mb) = probe_sysinfo();
43
44 let memory_pressure = classify_memory_pressure(available_memory_mb);
45 let worker_threads =
46 compute_worker_threads(logical_cpus, physical_cpus, available_memory_mb);
47 let progress_interval = compute_progress_interval(worker_threads);
48
49 Self {
50 logical_cpus,
51 physical_cpus,
52 total_memory_mb,
53 available_memory_mb,
54 worker_threads,
55 progress_interval,
56 memory_pressure,
57 measured_keys_per_sec: None,
58 }
59 }
60
61 pub fn with_benchmark(mut self, keys_per_sec: f64) -> Self {
63 self.measured_keys_per_sec = Some(keys_per_sec.max(1.0));
64 self
65 }
66
67 pub fn with_threads(mut self, threads: usize) -> Self {
69 let threads = threads.clamp(1, self.logical_cpus);
70 self.worker_threads = threads;
71 self.progress_interval = compute_progress_interval(threads);
72 self
73 }
74
75 pub fn summary_line(&self) -> String {
76 let cores = self.cpu_description();
77
78 format!(
79 "{cores} · {:.1} GB RAM ({:.1} GB free) · {} workers · memory: {}",
80 self.total_memory_mb as f64 / 1024.0,
81 self.available_memory_mb as f64 / 1024.0,
82 self.worker_threads,
83 self.memory_pressure,
84 )
85 }
86
87 pub fn cpu_description(&self) -> String {
88 match self.physical_cpus {
89 Some(physical) if physical != self.logical_cpus => {
90 format!("{} logical · {} physical", self.logical_cpus, physical)
91 }
92 Some(physical) => format!("{physical} cores"),
93 None => format!("{} cores", self.logical_cpus),
94 }
95 }
96
97 pub fn worker_description(&self) -> String {
98 let reserved = self.logical_cpus.saturating_sub(self.worker_threads);
99 if reserved > 0 {
100 format!(
101 "{} threads grinding · {} core{} reserved for OS",
102 self.worker_threads,
103 reserved,
104 if reserved == 1 { "" } else { "s" }
105 )
106 } else {
107 format!("{} threads (all cores)", self.worker_threads)
108 }
109 }
110
111 pub fn estimated_keys_per_sec(&self, chain_id: &str) -> f64 {
112 if let Some(measured) = self.measured_keys_per_sec {
113 return measured;
114 }
115 let per_thread = match chain_id {
116 "evm" | "evm-contract" | "trx-contract" | "create2" | "aptos" | "sui" | "near" => {
117 35_000.0
118 }
119 _ => 80_000.0,
120 };
121 per_thread * self.worker_threads as f64
122 }
123}
124
125fn probe_sysinfo() -> (Option<usize>, u64, u64) {
126 let mut sys = sysinfo::System::new();
127 sys.refresh_memory();
128
129 let total_memory_mb = sys.total_memory() / 1024 / 1024;
130 let mut available_memory_mb = sys.available_memory() / 1024 / 1024;
131
132 if available_memory_mb < 256 && total_memory_mb > 512 {
134 available_memory_mb = (total_memory_mb * 3) / 4;
135 }
136
137 let physical_cpus = sys.physical_core_count();
138
139 (physical_cpus, total_memory_mb, available_memory_mb)
140}
141
142fn classify_memory_pressure(available_mb: u64) -> MemoryPressure {
143 if available_mb < 512 {
144 MemoryPressure::Low
145 } else if available_mb < 2_048 {
146 MemoryPressure::Moderate
147 } else {
148 MemoryPressure::Comfortable
149 }
150}
151
152pub fn compute_worker_threads(
154 logical_cpus: usize,
155 physical_cpus: Option<usize>,
156 available_mem_mb: u64,
157) -> usize {
158 let logical_cpus = logical_cpus.max(1);
159
160 let mut threads = match logical_cpus {
162 1 => 1,
163 2 => 2,
164 n => n - 1,
165 };
166
167 if let Some(physical) = physical_cpus {
169 if physical > 0 && threads > physical {
170 threads = physical;
171 }
172 }
173
174 let mem_cap = match available_mem_mb {
176 m if m < 512 => 1,
177 m if m < 1_024 => 2,
178 m if m < 2_048 => 4,
179 m if m < 4_096 => 8,
180 _ => usize::MAX,
181 };
182
183 threads.min(mem_cap).max(1)
184}
185
186pub fn compute_progress_interval(worker_threads: usize) -> u64 {
188 (50_000_u64 * worker_threads as u64).clamp(100_000, 2_000_000)
189}
190
191pub fn build_thread_pool(profile: &SystemProfile) -> Result<rayon::ThreadPool, String> {
193 ThreadPoolBuilder::new()
194 .num_threads(profile.worker_threads)
195 .thread_name(|i| format!("vanity-worker-{i}"))
196 .build()
197 .map_err(|e| format!("Failed to configure thread pool: {e}"))
198}
199
200#[cfg(test)]
201mod tests {
202 use super::*;
203
204 #[test]
205 fn single_core_machine_uses_one_worker() {
206 assert_eq!(compute_worker_threads(1, Some(1), 16_384), 1);
207 }
208
209 #[test]
210 fn reserves_core_on_typical_laptop() {
211 assert_eq!(compute_worker_threads(8, Some(8), 16_384), 7);
212 }
213
214 #[test]
215 fn low_memory_caps_workers() {
216 assert_eq!(compute_worker_threads(16, Some(16), 800), 2);
217 }
218
219 #[test]
220 fn progress_interval_scales_with_threads() {
221 assert_eq!(compute_progress_interval(1), 100_000);
222 assert_eq!(compute_progress_interval(8), 400_000);
223 assert_eq!(compute_progress_interval(64), 2_000_000);
224 }
225}