1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
// Copyright 2025 Lablup Inc. and Jeongkyu Shin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Use native metrics manager for Apple Silicon
use crate::device::macos_native::get_native_metrics_manager;
// Intel Macs read temperature and package power straight from the SMC: the
// native metrics manager is IOReport-backed and therefore Apple Silicon only.
use crate::device::macos_native::smc::SmcConnection;
use crate::device::cpu_macos_intel::IntelCpuHardware;
use crate::device::{
AppleSiliconCpuInfo, CoreType, CoreUtilization, CpuInfo, CpuPlatformType, CpuReader,
CpuSocketInfo,
};
use crate::utils::command::new_command;
use crate::utils::system::get_hostname;
use chrono::Local;
use std::sync::{Mutex, RwLock};
use sysinfo::System;
/// (cpu_model, s_core_count, p_core_count, e_core_count, gpu_core_count)
type AppleSiliconHwInfo = (String, u32, u32, u32, u32);
pub struct MacOsCpuReader {
is_apple_silicon: bool,
// System info for CPU metrics (using RwLock for better concurrent read access)
system: RwLock<System>,
// Track if we've done the first refresh
first_refresh_done: RwLock<bool>,
// Cached hardware info for Apple Silicon
cached_cpu_model: Mutex<Option<String>>,
cached_s_core_count: Mutex<Option<u32>>,
cached_p_core_count: Mutex<Option<u32>>,
cached_e_core_count: Mutex<Option<u32>>,
cached_gpu_core_count: Mutex<Option<u32>>,
cached_s_core_l2_cache_mb: Mutex<Option<u32>>,
cached_p_core_l2_cache_mb: Mutex<Option<u32>>,
cached_e_core_l2_cache_mb: Mutex<Option<u32>>,
// Cached hardware info for Intel
cached_intel_info: Mutex<Option<IntelCpuHardware>>,
// Cached SMC connection, used by the Intel path only
smc: Mutex<SmcConnection>,
}
impl Default for MacOsCpuReader {
fn default() -> Self {
Self::new()
}
}
impl MacOsCpuReader {
pub fn new() -> Self {
let is_apple_silicon = Self::detect_apple_silicon();
let system = System::new();
Self {
is_apple_silicon,
system: RwLock::new(system),
first_refresh_done: RwLock::new(false),
cached_cpu_model: Mutex::new(None),
cached_s_core_count: Mutex::new(None),
cached_p_core_count: Mutex::new(None),
cached_e_core_count: Mutex::new(None),
cached_gpu_core_count: Mutex::new(None),
cached_s_core_l2_cache_mb: Mutex::new(None),
cached_p_core_l2_cache_mb: Mutex::new(None),
cached_e_core_l2_cache_mb: Mutex::new(None),
cached_intel_info: Mutex::new(None),
smc: Mutex::new(SmcConnection::default()),
}
}
/// Detect Apple Silicon through the shared, cached platform probe.
///
/// This used to be a second private copy of the `uname -m` check. Routing
/// it through `platform_detection` keeps a single answer per process, and
/// picks up the Rosetta 2 handling that copy did not have.
fn detect_apple_silicon() -> bool {
crate::device::platform_detection::is_apple_silicon()
}
fn get_cpu_info_from_system(&self) -> Result<CpuInfo, Box<dyn std::error::Error>> {
let hostname = get_hostname();
let instance = hostname.clone();
let time = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
if self.is_apple_silicon {
self.get_apple_silicon_cpu_info(hostname, instance, time)
} else {
self.get_intel_mac_cpu_info(hostname, instance, time)
}
}
fn get_apple_silicon_cpu_info(
&self,
hostname: String,
instance: String,
time: String,
) -> Result<CpuInfo, Box<dyn std::error::Error>> {
// Check cache BEFORE calling sysctl commands
// IMPORTANT: Read cache values first and drop the locks before any else branch
let cached_values = {
let cpu_model = self.cached_cpu_model.lock().unwrap().clone();
let s_core_count = *self.cached_s_core_count.lock().unwrap();
let p_core_count = *self.cached_p_core_count.lock().unwrap();
let e_core_count = *self.cached_e_core_count.lock().unwrap();
let gpu_core_count = *self.cached_gpu_core_count.lock().unwrap();
(
cpu_model,
s_core_count,
p_core_count,
e_core_count,
gpu_core_count,
)
};
// Now all locks are released
let (cpu_model, s_core_count, p_core_count, e_core_count, gpu_core_count) = if let (
Some(cpu_model),
Some(s_core_count),
Some(p_core_count),
Some(e_core_count),
Some(gpu_core_count),
) =
cached_values
{
// Use cached values - avoids sysctl/ioreg calls
(
cpu_model,
s_core_count,
p_core_count,
e_core_count,
gpu_core_count,
)
} else {
// Get CPU model and core counts using fast sysctl commands (first time only)
self.parse_apple_silicon_hardware_info_fast()?
};
// OPTIMIZATION: Refresh CPU usage ONCE and reuse for all subsequent reads
// This avoids multiple refresh_cpu_usage() calls which was causing high CPU usage
self.ensure_cpu_refreshed();
// Get actual CPU utilization (no refresh needed - already done above)
let cpu_utilization = self.system.read().unwrap().global_cpu_usage() as f64;
// OPTIMIZATION: Get native metrics ONCE and reuse for frequency/power/residency
// This avoids multiple collect_once() calls which was expensive
let native_data = get_native_metrics_manager().and_then(|m| m.collect_once().ok());
// Get CPU frequency information from cached native metrics
let (base_frequency, max_frequency, s_cluster_freq, p_cluster_freq, e_cluster_freq): (
u32,
u32,
Option<u32>,
Option<u32>,
Option<u32>,
) = {
if let Some(ref data) = native_data {
if s_core_count > 0 {
// M5 Pro/Max: Super + Performance (no Efficiency)
let avg_freq = (data.s_cluster_frequency + data.p_cluster_frequency) / 2;
(
avg_freq,
data.s_cluster_frequency, // S-cluster frequency as max
Some(data.s_cluster_frequency),
Some(data.p_cluster_frequency),
None, // No E-cluster on M5 Pro/Max
)
} else {
// M1-M4: Performance + Efficiency
let avg_freq = (data.p_cluster_frequency + data.e_cluster_frequency) / 2;
(
avg_freq,
data.p_cluster_frequency, // P-cluster frequency as max
None,
Some(data.p_cluster_frequency),
Some(data.e_cluster_frequency),
)
}
} else {
(
self.get_cpu_base_frequency()?,
self.get_cpu_max_frequency()?,
None,
None,
None,
)
}
};
// Get per-core utilization (no refresh needed - already done above)
let per_core_utilization = self.get_per_core_utilization_no_refresh(
s_core_count as usize,
e_core_count as usize,
p_core_count as usize,
);
// Get CPU temperature from cached native metrics (SMC sensor reading).
// Falls back to None if SMC didn't return a usable value.
let temperature = native_data
.as_ref()
.and_then(|d| d.cpu_temperature)
.map(|t| t.round() as u32);
// Power consumption from cached native metrics
let power_consumption = native_data.as_ref().map(|d| d.cpu_power_mw / 1000.0);
let total_cores = s_core_count + p_core_count + e_core_count;
let total_threads = total_cores; // Apple Silicon doesn't use hyperthreading
// Get cache sizes for S, P and E cores
let s_core_l2_cache_mb = self.get_s_core_l2_cache_size().ok();
let p_core_l2_cache_mb = self.get_p_core_l2_cache_size().ok();
let e_core_l2_cache_mb = self.get_e_core_l2_cache_size().ok();
// Calculate S-core, P-core and E-core utilization from per-core data if available
let (s_core_utilization, p_core_utilization, e_core_utilization) =
if !per_core_utilization.is_empty() {
let mut s_sum = 0.0;
let mut s_count = 0;
let mut p_sum = 0.0;
let mut p_count = 0;
let mut e_sum = 0.0;
let mut e_count = 0;
for core in &per_core_utilization {
match core.core_type {
CoreType::Super => {
s_sum += core.utilization;
s_count += 1;
}
CoreType::Performance => {
p_sum += core.utilization;
p_count += 1;
}
CoreType::Efficiency => {
e_sum += core.utilization;
e_count += 1;
}
_ => {}
}
}
let s_util = if s_count > 0 {
s_sum / s_count as f64
} else {
0.0
};
let p_util = if p_count > 0 {
p_sum / p_count as f64
} else {
cpu_utilization * 0.6
};
let e_util = if e_count > 0 {
e_sum / e_count as f64
} else if s_core_count > 0 {
// M5 Pro/Max has no E-cores, so no fallback needed
0.0
} else {
cpu_utilization * 0.4
};
(s_util, p_util, e_util)
} else {
// Fallback to estimated values
let (p_util, e_util) = self
.get_apple_silicon_core_utilization()
.unwrap_or((cpu_utilization * 0.6, cpu_utilization * 0.4));
(0.0, p_util, e_util)
};
let apple_silicon_info = Some(AppleSiliconCpuInfo {
s_core_count,
p_core_count,
e_core_count,
gpu_core_count,
s_core_utilization,
p_core_utilization,
e_core_utilization,
ane_ops_per_second: None, // ANE metrics are complex to get
s_cluster_frequency_mhz: s_cluster_freq,
p_cluster_frequency_mhz: p_cluster_freq,
e_cluster_frequency_mhz: e_cluster_freq,
s_core_l2_cache_mb,
p_core_l2_cache_mb,
e_core_l2_cache_mb,
});
// Create per-socket info (Apple Silicon typically has 1 socket)
let per_socket_info = vec![CpuSocketInfo {
socket_id: 0,
utilization: cpu_utilization,
cores: total_cores,
threads: total_threads,
temperature,
frequency_mhz: base_frequency,
}];
Ok(CpuInfo {
index: 0, // Overwritten by AllSmi::get_cpu_info when flattening readers
host_id: hostname.clone(), // For local mode, host_id is just the hostname
hostname,
instance,
cpu_model,
architecture: "arm64".to_string(),
platform_type: CpuPlatformType::AppleSilicon,
socket_count: 1,
total_cores,
total_threads,
base_frequency_mhz: base_frequency,
max_frequency_mhz: max_frequency,
cache_size_mb: s_core_l2_cache_mb.unwrap_or(0)
+ p_core_l2_cache_mb.unwrap_or(0)
+ e_core_l2_cache_mb.unwrap_or(0), // Total L2 cache
utilization: cpu_utilization,
temperature,
power_consumption,
per_socket_info,
apple_silicon_info,
per_core_utilization,
time,
})
}
fn get_intel_mac_cpu_info(
&self,
hostname: String,
instance: String,
time: String,
) -> Result<CpuInfo, Box<dyn std::error::Error>> {
let hardware = self.get_intel_hardware_info();
// Refresh once per collection cycle, then reuse the snapshot for both
// the aggregate and the per-core numbers.
self.ensure_cpu_refreshed();
let cpu_utilization = self.system.read().unwrap().global_cpu_usage() as f64;
// Intel cores are homogeneous, so no P/E/S split applies: passing zero
// for every Apple Silicon cluster size makes every core Standard.
let per_core_utilization = self.get_per_core_utilization_no_refresh(0, 0, 0);
// CPU temperature and package power come from the SMC over the cached
// connection. Both are absent on some models, which is not an error.
let (temperature, power_consumption) = self.read_intel_smc_metrics();
let socket_count = hardware.socket_count.max(1);
// Create per-socket info
let mut per_socket_info = Vec::new();
for socket_id in 0..socket_count {
per_socket_info.push(CpuSocketInfo {
socket_id,
utilization: cpu_utilization,
cores: hardware.physical_cores / socket_count,
threads: hardware.logical_cores / socket_count,
temperature,
frequency_mhz: hardware.base_frequency_mhz,
});
}
Ok(CpuInfo {
index: 0, // Overwritten by AllSmi::get_cpu_info when flattening readers
host_id: hostname.clone(), // For local mode, host_id is just the hostname
hostname,
instance,
cpu_model: hardware.model.clone(),
architecture: "x86_64".to_string(),
platform_type: CpuPlatformType::Intel,
socket_count,
total_cores: hardware.physical_cores,
total_threads: hardware.logical_cores,
base_frequency_mhz: hardware.base_frequency_mhz,
max_frequency_mhz: hardware.max_frequency_mhz,
cache_size_mb: hardware.l3_cache_mb,
utilization: cpu_utilization,
temperature,
power_consumption,
per_socket_info,
apple_silicon_info: None,
per_core_utilization,
time,
})
}
/// Read CPU temperature (Celsius) and package power (watts) from the SMC.
///
/// Both readings share one cached connection so a poll costs two key reads
/// rather than a fresh IOKit handshake.
fn read_intel_smc_metrics(&self) -> (Option<u32>, Option<f64>) {
let Ok(mut guard) = self.smc.lock() else {
return (None, None);
};
let Some(smc) = guard.get() else {
return (None, None);
};
let temperature = smc.get_cpu_temperature().map(|t| t.round() as u32);
let power = smc.get_cpu_package_power();
(temperature, power)
}
/// Collect the immutable Intel CPU hardware description, caching it.
///
/// Discovery itself lives in `cpu_macos_intel`; this only owns the cache.
fn get_intel_hardware_info(&self) -> IntelCpuHardware {
if let Some(cached) = self.cached_intel_info.lock().unwrap().clone() {
return cached;
}
// Last-resort thread count, used only when `hw.logicalcpu` is missing.
// Deliberately not `self.system.cpus().len()`: this runs before the
// first `ensure_cpu_refreshed`, and a freshly constructed `System` has
// an empty CPU list, so that source reports 0 and the result would be
// cached for the process lifetime.
let logical_cpu_fallback = std::thread::available_parallelism()
.map(|n| n.get() as u32)
.unwrap_or(0);
let hardware = IntelCpuHardware::collect(logical_cpu_fallback);
*self.cached_intel_info.lock().unwrap() = Some(hardware.clone());
hardware
}
/// Fast method to get Apple Silicon hardware info using sysctl and ioreg
/// This is ~50x faster than system_profiler (~10ms vs ~500ms)
/// Returns (cpu_model, s_core_count, p_core_count, e_core_count, gpu_core_count)
fn parse_apple_silicon_hardware_info_fast(
&self,
) -> Result<AppleSiliconHwInfo, Box<dyn std::error::Error>> {
// Check if we have cached values
if let (
Some(cpu_model),
Some(s_core_count),
Some(p_core_count),
Some(e_core_count),
Some(gpu_core_count),
) = (
self.cached_cpu_model.lock().unwrap().clone(),
*self.cached_s_core_count.lock().unwrap(),
*self.cached_p_core_count.lock().unwrap(),
*self.cached_e_core_count.lock().unwrap(),
*self.cached_gpu_core_count.lock().unwrap(),
) {
return Ok((
cpu_model,
s_core_count,
p_core_count,
e_core_count,
gpu_core_count,
));
}
// Get CPU model using sysctl (fast: ~10ms vs system_profiler ~500ms)
let cpu_model = self.get_cpu_model_sysctl()?;
// Read perflevel names and core counts to determine core types dynamically
// M5 Pro/Max: perflevel0.name=Super, perflevel1.name=Performance (no E-cores)
// M1-M4: perflevel0.name=Performance (or absent), perflevel1.name=Efficiency
let output = new_command("sysctl")
.args(["hw.perflevel0.physicalcpu", "hw.perflevel1.physicalcpu"])
.output()?;
let output_str = String::from_utf8_lossy(&output.stdout);
let mut perflevel0_count = 0u32;
let mut perflevel1_count = 0u32;
for line in output_str.lines() {
if line.starts_with("hw.perflevel0.physicalcpu:") {
if let Some(value) = line.split(':').nth(1) {
perflevel0_count = value.trim().parse().unwrap_or(0);
}
} else if line.starts_with("hw.perflevel1.physicalcpu:")
&& let Some(value) = line.split(':').nth(1)
{
perflevel1_count = value.trim().parse().unwrap_or(0);
}
}
// Read perflevel0 name to detect Super cores (M5 Pro/Max)
let perflevel0_name = Self::get_perflevel_name(0);
let (s_core_count, p_core_count, e_core_count) =
if perflevel0_name.as_deref() == Some("Super") {
// M5 Pro/Max: perflevel0 = Super, perflevel1 = Performance, no E-cores
(perflevel0_count, perflevel1_count, 0u32)
} else {
// M1-M4 (legacy): perflevel0 = P-cores, perflevel1 = E-cores
(0u32, perflevel0_count, perflevel1_count)
};
// Get GPU core count using ioreg (fast: ~50ms vs system_profiler ~500ms)
let gpu_core_count = self.get_gpu_core_count_ioreg().unwrap_or(0);
// Validate we got valid counts
// M5 Pro/Max has 0 E-cores, so only check that at least one core type is non-zero
if (s_core_count + p_core_count) == 0 {
return Err("Failed to get core counts".into());
}
// Cache the values
*self.cached_cpu_model.lock().unwrap() = Some(cpu_model.clone());
*self.cached_s_core_count.lock().unwrap() = Some(s_core_count);
*self.cached_p_core_count.lock().unwrap() = Some(p_core_count);
*self.cached_e_core_count.lock().unwrap() = Some(e_core_count);
*self.cached_gpu_core_count.lock().unwrap() = Some(gpu_core_count);
Ok((
cpu_model,
s_core_count,
p_core_count,
e_core_count,
gpu_core_count,
))
}
/// Read hw.perflevelN.name via sysctl to determine core type names
/// Returns None if the sysctl key does not exist (M1-M4 chips)
fn get_perflevel_name(level: u32) -> Option<String> {
let key = format!("hw.perflevel{level}.name");
let output = new_command("sysctl").args(["-n", &key]).output().ok()?;
if !output.status.success() {
return None;
}
let name = String::from_utf8_lossy(&output.stdout).trim().to_string();
if name.is_empty() { None } else { Some(name) }
}
/// Get CPU model from sysctl machdep.cpu.brand_string
/// This is significantly faster than system_profiler (~10ms vs ~500ms)
fn get_cpu_model_sysctl(&self) -> Result<String, Box<dyn std::error::Error>> {
let output = new_command("sysctl")
.args(["-n", "machdep.cpu.brand_string"])
.output()?;
let cpu_brand = String::from_utf8_lossy(&output.stdout).trim().to_string();
// Extract chip name from brand string
// e.g., "Apple M2 Pro" -> "Apple M2 Pro"
if cpu_brand.starts_with("Apple M") {
Ok(cpu_brand)
} else if cpu_brand.is_empty() {
Err("Failed to get CPU model from sysctl".into())
} else {
// For other cases, return as-is
Ok(cpu_brand)
}
}
/// Get GPU core count using ioreg (faster than system_profiler)
fn get_gpu_core_count_ioreg(&self) -> Result<u32, Box<dyn std::error::Error>> {
let output = new_command("ioreg")
.args(["-rc", "AGXAccelerator", "-d1"])
.output()?;
let output_str = String::from_utf8_lossy(&output.stdout);
// Look for "gpu-core-count" in ioreg output
for line in output_str.lines() {
if line.contains("\"gpu-core-count\"") {
// Format: "gpu-core-count" = 10
let parts: Vec<&str> = line.split('=').collect();
if parts.len() >= 2
&& let Ok(count) = parts[1].trim().parse::<u32>()
{
return Ok(count);
}
}
}
// Fallback: estimate from CPU model
self.estimate_gpu_cores_from_model()
}
/// Estimate GPU core count from CPU model name
fn estimate_gpu_cores_from_model(&self) -> Result<u32, Box<dyn std::error::Error>> {
if let Some(cpu_model) = self.cached_cpu_model.lock().unwrap().clone() {
let model = cpu_model.as_str();
let core_count = match model {
s if s.contains("M1 ")
&& !s.contains("Pro")
&& !s.contains("Max")
&& !s.contains("Ultra") =>
{
8
}
s if s.contains("M1 Pro") => 16,
s if s.contains("M1 Max") => 32,
s if s.contains("M1 Ultra") => 64,
s if s.contains("M2 ")
&& !s.contains("Pro")
&& !s.contains("Max")
&& !s.contains("Ultra") =>
{
10
}
s if s.contains("M2 Pro") => 19,
s if s.contains("M2 Max") => 38,
s if s.contains("M2 Ultra") => 76,
s if s.contains("M3 ") && !s.contains("Pro") && !s.contains("Max") => 10,
s if s.contains("M3 Pro") => 18,
s if s.contains("M3 Max") => 40,
s if s.contains("M4 ") && !s.contains("Pro") && !s.contains("Max") => 10,
s if s.contains("M4 Pro") => 20,
s if s.contains("M4 Max") => 40,
_ => 8, // Default fallback
};
return Ok(core_count);
}
Err("Cannot estimate GPU cores without CPU model".into())
}
// These methods are no longer used since we fetch both values in a single sysctl call
#[allow(dead_code)]
fn get_p_core_count(&self) -> Result<u32, Box<dyn std::error::Error>> {
let output = new_command("sysctl")
.arg("hw.perflevel0.physicalcpu")
.output()?;
let output_str = String::from_utf8_lossy(&output.stdout);
if let Some(value_str) = output_str.split(':').nth(1) {
let count = value_str.trim().parse::<u32>()?;
Ok(count)
} else {
Err("Failed to parse P-core count".into())
}
}
#[allow(dead_code)]
fn get_e_core_count(&self) -> Result<u32, Box<dyn std::error::Error>> {
let output = new_command("sysctl")
.arg("hw.perflevel1.physicalcpu")
.output()?;
let output_str = String::from_utf8_lossy(&output.stdout);
if let Some(value_str) = output_str.split(':').nth(1) {
let count = value_str.trim().parse::<u32>()?;
Ok(count)
} else {
Err("Failed to parse E-core count".into())
}
}
#[allow(dead_code)] // Kept as fallback, but get_gpu_core_count_ioreg() is preferred
fn get_gpu_core_count(&self) -> Result<u32, Box<dyn std::error::Error>> {
let output = new_command("system_profiler")
.arg("SPDisplaysDataType")
.arg("-json")
.output()?;
let output_str = String::from_utf8_lossy(&output.stdout);
// Parse JSON to find GPU core count
// Look for "sppci_cores" field in the JSON output
for line in output_str.lines() {
if line.contains("sppci_cores") {
// Extract the value between quotes after the colon
if let Some(value_part) = line.split(':').nth(1)
&& let Some(start_quote) = value_part.find('"')
&& let Some(end_quote) = value_part[start_quote + 1..].find('"')
{
let core_str = &value_part[start_quote + 1..start_quote + 1 + end_quote];
if let Ok(count) = core_str.parse::<u32>() {
return Ok(count);
}
}
}
}
Err("Failed to parse GPU core count".into())
}
/// Get S-core (Super) L2 cache size from perflevel0 on M5 Pro/Max
/// On M1-M4, this returns Err since perflevel0 is P-cores there (handled by get_p_core_l2_cache_size)
fn get_s_core_l2_cache_size(&self) -> Result<u32, Box<dyn std::error::Error>> {
// Only valid on M5 Pro/Max where Super cores exist
if *self.cached_s_core_count.lock().unwrap() == Some(0) {
return Err("No Super cores on this chip".into());
}
if let Some(cached) = *self.cached_s_core_l2_cache_mb.lock().unwrap() {
return Ok(cached);
}
// On M5 Pro/Max, perflevel0 = Super cores
let output = new_command("sysctl")
.arg("hw.perflevel0.l2cachesize")
.output()?;
let output_str = String::from_utf8_lossy(&output.stdout);
if let Some(value_str) = output_str.split(':').nth(1) {
let cache_bytes = value_str.trim().parse::<u64>()?;
let cache_mb = (cache_bytes / 1024 / 1024) as u32;
*self.cached_s_core_l2_cache_mb.lock().unwrap() = Some(cache_mb);
Ok(cache_mb)
} else {
Err("Failed to parse S-core L2 cache size".into())
}
}
fn get_p_core_l2_cache_size(&self) -> Result<u32, Box<dyn std::error::Error>> {
// Check if we have cached value
if let Some(cached) = *self.cached_p_core_l2_cache_mb.lock().unwrap() {
return Ok(cached);
}
// On M5 Pro/Max (has Super cores), P-cores are perflevel1
// On M1-M4, P-cores are perflevel0
let s_count = *self.cached_s_core_count.lock().unwrap();
let has_super = s_count.is_some() && s_count != Some(0);
let perflevel = if has_super {
"hw.perflevel1.l2cachesize"
} else {
"hw.perflevel0.l2cachesize"
};
let output = new_command("sysctl").arg(perflevel).output()?;
let output_str = String::from_utf8_lossy(&output.stdout);
if let Some(value_str) = output_str.split(':').nth(1) {
let cache_bytes = value_str.trim().parse::<u64>()?;
let cache_mb = (cache_bytes / 1024 / 1024) as u32; // Convert bytes to MB
// Cache the value
*self.cached_p_core_l2_cache_mb.lock().unwrap() = Some(cache_mb);
Ok(cache_mb)
} else {
Err("Failed to parse P-core L2 cache size".into())
}
}
fn get_e_core_l2_cache_size(&self) -> Result<u32, Box<dyn std::error::Error>> {
// M5 Pro/Max has no E-cores — skip if Super cores are present
{
let s_count = self.cached_s_core_count.lock().unwrap();
if matches!(*s_count, Some(n) if n > 0) {
return Err("No E-cores on M5 Pro/Max".into());
}
}
// Check if we have cached value
if let Some(cached) = *self.cached_e_core_l2_cache_mb.lock().unwrap() {
return Ok(cached);
}
// On M1-M4, E-cores are perflevel1
let output = new_command("sysctl")
.arg("hw.perflevel1.l2cachesize")
.output()?;
let output_str = String::from_utf8_lossy(&output.stdout);
if let Some(value_str) = output_str.split(':').nth(1) {
let cache_bytes = value_str.trim().parse::<u64>()?;
let cache_mb = (cache_bytes / 1024 / 1024) as u32; // Convert bytes to MB
// Cache the value
*self.cached_e_core_l2_cache_mb.lock().unwrap() = Some(cache_mb);
Ok(cache_mb)
} else {
Err("Failed to parse E-core L2 cache size".into())
}
}
/// OPTIMIZATION: Refresh CPU usage once per collection cycle
/// This avoids multiple refresh_cpu_usage() calls which was causing high CPU usage
fn ensure_cpu_refreshed(&self) {
// Check if we need to do first refresh with initialization delay
if !*self.first_refresh_done.read().unwrap() {
self.system.write().unwrap().refresh_cpu_usage();
std::thread::sleep(std::time::Duration::from_millis(100));
*self.first_refresh_done.write().unwrap() = true;
}
// Single refresh per collection cycle
self.system.write().unwrap().refresh_cpu_usage();
}
#[allow(dead_code)] // Kept as fallback method when sysinfo is unavailable
fn get_cpu_utilization_iostat(&self) -> Result<f64, Box<dyn std::error::Error>> {
// Fallback method using iostat (kept for compatibility)
let output = new_command("iostat").args(["-c", "1"]).output()?;
let iostat_output = String::from_utf8_lossy(&output.stdout);
// Parse CPU utilization from iostat output
for line in iostat_output.lines() {
if line.contains("avg-cpu") {
continue;
}
if line
.trim()
.chars()
.next()
.is_some_and(|c| c.is_ascii_digit())
{
let fields: Vec<&str> = line.split_whitespace().collect();
if fields.len() >= 6 {
// iostat format: %user %nice %system %iowait %steal %idle
let idle = fields[5].parse::<f64>().unwrap_or(0.0);
return Ok(100.0 - idle);
}
}
}
Ok(0.0)
}
fn get_apple_silicon_core_utilization(&self) -> Result<(f64, f64), Box<dyn std::error::Error>> {
// OPTIMIZATION: This is a fallback method only called when per_core_utilization is empty
// Don't refresh CPU here since caller (get_apple_silicon_cpu_info) already did via ensure_cpu_refreshed()
let total_cpu_util = self.system.read().unwrap().global_cpu_usage() as f64;
// Use native metrics manager for cluster residency (cached, no extra collection)
if let Some(manager) = get_native_metrics_manager()
&& let Ok(data) = manager.collect_once()
{
// Use cluster residency from native metrics
let p_residency = data.p_cluster_active_residency.clamp(0.0, 100.0);
let e_residency = data.e_cluster_active_residency.clamp(0.0, 100.0);
let total_residency = p_residency + e_residency;
if total_residency > 0.0 {
let p_ratio = p_residency / total_residency;
let e_ratio = e_residency / total_residency;
return Ok((
(total_cpu_util * p_ratio * 1.2).clamp(0.0, 100.0),
(total_cpu_util * e_ratio * 0.8).clamp(0.0, 100.0),
));
}
}
// Return default values if manager is not available
// Split total utilization evenly
Ok((total_cpu_util * 0.6, total_cpu_util * 0.4))
}
fn get_cpu_base_frequency(&self) -> Result<u32, Box<dyn std::error::Error>> {
if self.is_apple_silicon {
// Apple Silicon base frequencies are not easily available
// Return typical values based on chip
Ok(3000) // 3 GHz as default
} else {
// Intel: the real nominal clock, from hw.cpufrequency or the brand
// string, instead of a hardcoded constant.
Ok(self.get_intel_hardware_info().base_frequency_mhz)
}
}
fn get_cpu_max_frequency(&self) -> Result<u32, Box<dyn std::error::Error>> {
if self.is_apple_silicon {
// Apple Silicon max frequencies vary by core type
Ok(3500) // Typical P-core max frequency
} else {
// Intel: hw.cpufrequency_max, falling back to the base clock when
// the key is absent (see IntelCpuHardware::apply_defaults).
Ok(self.get_intel_hardware_info().max_frequency_mhz)
}
}
#[allow(dead_code)] // OPTIMIZATION: Now using cached native_data instead
fn get_cpu_power_consumption(&self) -> Option<f64> {
// Use native metrics manager
if let Some(manager) = get_native_metrics_manager()
&& let Ok(data) = manager.collect_once()
{
return Some(data.cpu_power_mw / 1000.0); // Convert mW to W
}
None
}
/// Get per-core CPU utilization using sysinfo (with refresh)
/// For Apple Silicon M1-M4: E-cores first (0 to e_core_count-1), then P-cores
/// For Apple Silicon M5: E-cores first (0, always empty), then P-cores, then S-cores
#[allow(dead_code)] // Kept for potential future use when refresh is needed
fn get_per_core_utilization(
&self,
s_core_count: usize,
e_core_count: usize,
p_core_count: usize,
) -> Vec<CoreUtilization> {
// Refresh CPU usage to get latest data
self.system.write().unwrap().refresh_cpu_usage();
self.get_per_core_utilization_no_refresh(s_core_count, e_core_count, p_core_count)
}
/// Get per-core CPU utilization WITHOUT refreshing CPU data
/// OPTIMIZATION: Used when CPU has already been refreshed via ensure_cpu_refreshed()
/// For Apple Silicon M1-M4: E-cores first (indices 0 to e_core_count-1), then P-cores
/// For Apple Silicon M5 Pro/Max: S-cores first (indices 0 to s_core_count-1), then P-cores
fn get_per_core_utilization_no_refresh(
&self,
s_core_count: usize,
e_core_count: usize,
p_core_count: usize,
) -> Vec<CoreUtilization> {
let mut per_core_utilization = Vec::new();
let system = self.system.read().unwrap();
let cpus = system.cpus();
let has_super = s_core_count > 0;
for (core_id, cpu) in cpus.iter().enumerate() {
let utilization = cpu.cpu_usage() as f64;
// Determine core type based on index and chip architecture
let core_type = if self.is_apple_silicon {
if has_super {
// M5 Pro/Max layout: S-cores first, then P-cores
// sysinfo reports cores in perflevel order:
// perflevel0 (Super) first, then perflevel1 (Performance)
if core_id < s_core_count {
CoreType::Super
} else if core_id < s_core_count + p_core_count {
CoreType::Performance
} else {
CoreType::Standard
}
} else {
// M1-M4 layout: E-cores first, then P-cores
if core_id < e_core_count {
CoreType::Efficiency
} else if core_id < e_core_count + p_core_count {
CoreType::Performance
} else {
CoreType::Standard
}
}
} else {
CoreType::Standard // Intel Macs use standard cores
};
per_core_utilization.push(CoreUtilization {
core_id: core_id as u32,
core_type,
utilization,
});
}
per_core_utilization
}
}
impl CpuReader for MacOsCpuReader {
fn get_cpu_info(&self) -> Vec<CpuInfo> {
match self.get_cpu_info_from_system() {
Ok(cpu_info) => {
vec![cpu_info]
}
Err(e) => {
eprintln!("Error reading CPU info: {e}");
vec![]
}
}
}
}