1use core::fmt;
16use std::sync::OnceLock;
17
18use crate::{Mhz, Pressure, Result, mem::LimitSource, os::keep, parse::cpu_name};
19
20mod features;
21mod topology;
22mod usage;
23
24pub use features::{Feature, Features, X86Level, features, has, x86_level};
25pub use topology::{
26 Cache, CacheKind, Core, CoreKind, NumaNode, Package, Topology, cache_line, caches, is_hybrid,
27 numa_nodes, topology,
28};
29pub(crate) use usage::States;
30pub use usage::{DEFAULT_WINDOW, Sampler, Times, Usage, free, times, usage, usage_over, used};
31
32#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
34#[non_exhaustive]
35pub enum Arch {
36 X86_64,
38 X86,
40 Aarch64,
42 Arm,
44 Riscv64,
46 Powerpc64,
48 S390x,
50 Loongarch64,
52 Wasm32,
54 Other,
56}
57
58impl Arch {
59 #[must_use]
65 pub const fn name(self) -> &'static str {
66 match self {
67 Self::X86_64 => "x86_64",
68 Self::X86 => "x86",
69 Self::Aarch64 => "aarch64",
70 Self::Arm => "arm",
71 Self::Riscv64 => "riscv64",
72 Self::Powerpc64 => "powerpc64",
73 Self::S390x => "s390x",
74 Self::Loongarch64 => "loongarch64",
75 Self::Wasm32 => "wasm32",
76 Self::Other => "other",
77 }
78 }
79
80 #[must_use]
88 pub const fn is_64bit(self) -> bool {
89 matches!(
90 self,
91 Self::X86_64
92 | Self::Aarch64
93 | Self::Riscv64
94 | Self::Powerpc64
95 | Self::S390x
96 | Self::Loongarch64
97 )
98 }
99}
100
101#[must_use]
103pub const fn arch() -> Arch {
104 if cfg!(target_arch = "x86_64") {
105 Arch::X86_64
106 } else if cfg!(target_arch = "x86") {
107 Arch::X86
108 } else if cfg!(target_arch = "aarch64") {
109 Arch::Aarch64
110 } else if cfg!(target_arch = "arm") {
111 Arch::Arm
112 } else if cfg!(target_arch = "riscv64") {
113 Arch::Riscv64
114 } else if cfg!(target_arch = "powerpc64") {
115 Arch::Powerpc64
116 } else if cfg!(target_arch = "s390x") {
117 Arch::S390x
118 } else if cfg!(target_arch = "loongarch64") {
119 Arch::Loongarch64
120 } else if cfg!(target_arch = "wasm32") {
121 Arch::Wasm32
122 } else {
123 Arch::Other
124 }
125}
126
127#[must_use]
135pub fn is_64bit() -> bool {
136 static IS_64: OnceLock<bool> = OnceLock::new();
137 *IS_64.get_or_init(crate::sys::processor_is_64bit)
138}
139
140#[must_use]
142pub fn is_32bit() -> bool {
143 !is_64bit()
144}
145
146#[must_use]
153pub fn native_arch() -> Arch {
154 static ARCH: OnceLock<Arch> = OnceLock::new();
155 *ARCH.get_or_init(crate::sys::native_arch)
156}
157
158#[must_use]
161pub fn is_translated() -> bool {
162 native_arch() != arch()
163}
164
165#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
167#[non_exhaustive]
168pub enum Vendor {
169 Intel,
171 Amd,
173 Apple,
175 Arm,
177 Qualcomm,
179 Ampere,
181 Nvidia,
183 Samsung,
185 Mediatek,
187 Hygon,
189 Zhaoxin,
191 Broadcom,
193 Marvell,
195 Fujitsu,
197 HiSilicon,
199 Microsoft,
201 #[default]
203 Unknown,
204}
205
206impl Vendor {
207 #[must_use]
209 pub const fn name(self) -> &'static str {
210 match self {
211 Self::Intel => "Intel",
212 Self::Amd => "AMD",
213 Self::Apple => "Apple",
214 Self::Arm => "ARM",
215 Self::Qualcomm => "Qualcomm",
216 Self::Ampere => "Ampere",
217 Self::Nvidia => "NVIDIA",
218 Self::Samsung => "Samsung",
219 Self::Mediatek => "MediaTek",
220 Self::Hygon => "Hygon",
221 Self::Zhaoxin => "Zhaoxin",
222 Self::Broadcom => "Broadcom",
223 Self::Marvell => "Marvell",
224 Self::Fujitsu => "Fujitsu",
225 Self::HiSilicon => "HiSilicon",
226 Self::Microsoft => "Microsoft",
227 Self::Unknown => "unknown",
228 }
229 }
230}
231
232struct Static {
233 logical: usize,
234 physical: usize,
235 physical_exact: bool,
236 packages: usize,
237 name: &'static str,
238 raw_name: Option<&'static str>,
239 vendor: Vendor,
240}
241
242fn facts() -> &'static Static {
243 static FACTS: OnceLock<Static> = OnceLock::new();
244 FACTS.get_or_init(|| build(crate::sys::cpu()))
245}
246
247fn build(f: crate::sys::CpuFacts) -> Static {
248 let logical = f.logical.max(1);
249 let physical = f.physical.unwrap_or(logical).clamp(1, logical);
250 let packages = f.packages.unwrap_or(1).clamp(1, physical);
251 let name = f
252 .name
253 .or_else(|| f.raw_name.as_deref().map(cpu_name::clean))
254 .filter(|n| !n.is_empty())
255 .unwrap_or_else(|| match f.vendor {
256 Vendor::Unknown => "unknown".to_owned(),
257 v => format!("{} {}", v.name(), arch().name()),
258 });
259 Static {
260 logical,
261 physical,
262 physical_exact: f.physical.is_some(),
263 packages,
264 name: keep(name),
265 raw_name: f.raw_name.filter(|n| !n.trim().is_empty()).map(keep),
266 vendor: f.vendor,
267 }
268}
269
270#[must_use]
274pub fn logical() -> usize {
275 facts().logical
276}
277
278#[must_use]
281pub fn physical() -> usize {
282 facts().physical
283}
284
285#[must_use]
291pub fn available() -> usize {
292 crate::sys::cpu_available(logical()).clamp(1, logical())
293}
294
295#[must_use]
299pub fn name() -> &'static str {
300 facts().name
301}
302
303#[must_use]
306pub fn raw_name() -> Option<&'static str> {
307 facts().raw_name
308}
309
310#[must_use]
312pub fn vendor() -> Vendor {
313 facts().vendor
314}
315
316#[must_use]
319pub fn packages() -> usize {
320 facts().packages
321}
322
323#[must_use]
327pub fn online() -> usize {
328 crate::sys::cpu_online(logical()).clamp(1, logical())
329}
330
331#[derive(Clone, Copy, PartialEq, Eq, Debug)]
333#[non_exhaustive]
334pub struct Counts {
335 pub logical: usize,
337 pub physical: usize,
339 pub packages: usize,
341 pub available: usize,
343 pub online: usize,
345 pub physical_exact: bool,
348}
349
350#[must_use]
357pub fn count() -> Counts {
358 let f = facts();
359 Counts {
360 logical: f.logical,
361 physical: f.physical,
362 packages: f.packages,
363 available: available(),
364 online: online(),
365 physical_exact: f.physical_exact,
366 }
367}
368
369#[derive(Clone, Copy, PartialEq, Debug)]
371#[non_exhaustive]
372pub struct CpuQuota {
373 pub cpus: f32,
375 pub source: LimitSource,
377}
378
379pub fn quota() -> Result<Option<CpuQuota>> {
396 crate::sys::cpu_quota()
397}
398
399#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
401#[non_exhaustive]
402pub struct Frequency {
403 pub base: Option<Mhz>,
405 pub max: Option<Mhz>,
407}
408
409#[must_use]
417pub fn frequency() -> &'static Frequency {
418 static FREQUENCY: OnceLock<Frequency> = OnceLock::new();
419 FREQUENCY.get_or_init(crate::sys::frequency)
420}
421
422pub fn current_frequency() -> Result<Option<Mhz>> {
430 crate::sys::current_frequency()
431}
432
433#[derive(Clone, Copy, PartialEq, Debug)]
441#[non_exhaustive]
442pub struct Load {
443 pub one: f32,
445 pub five: f32,
447 pub fifteen: f32,
449}
450
451impl Load {
452 pub(crate) fn new(one: f32, five: f32, fifteen: f32) -> Load {
453 let clean = |v: f32| if v.is_finite() { v.max(0.0) } else { 0.0 };
454 Load {
455 one: clean(one),
456 five: clean(five),
457 fifteen: clean(fifteen),
458 }
459 }
460
461 #[must_use]
470 pub fn per_cpu(&self) -> Load {
471 let n = logical() as f32;
472 Load::new(self.one / n, self.five / n, self.fifteen / n)
473 }
474}
475
476impl fmt::Display for Load {
477 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
478 write!(f, "{:.2} {:.2} {:.2}", self.one, self.five, self.fifteen)
479 }
480}
481
482pub fn load() -> Result<Option<Load>> {
498 crate::sys::load()
499}
500
501pub fn pressure() -> Result<Option<Pressure>> {
511 crate::sys::cpu_pressure()
512}
513
514#[cfg(test)]
515mod tests {
516 use super::*;
517
518 fn facts_with(
519 logical: usize,
520 physical: Option<usize>,
521 raw: Option<&str>,
522 name: Option<&str>,
523 vendor: Vendor,
524 ) -> Static {
525 build(crate::sys::CpuFacts {
526 logical,
527 physical,
528 packages: None,
529 raw_name: raw.map(str::to_owned),
530 name: name.map(str::to_owned),
531 vendor,
532 })
533 }
534
535 #[test]
536 fn test_cpu_counts_hold_their_invariants() {
537 assert!(physical() >= 1 && physical() <= logical());
538 let a = available();
539 assert!(a >= 1 && a <= logical());
540 assert_ne!(is_64bit(), is_32bit());
541 if arch().is_64bit() {
542 assert!(is_64bit());
543 }
544 assert!(!name().is_empty());
545 }
546
547 #[test]
548 fn test_cpu_build_cleans_and_falls_back() {
549 let s = facts_with(
550 8,
551 Some(4),
552 Some("Intel(R) Core(TM) i7-8700 CPU @ 3.20GHz"),
553 None,
554 Vendor::Intel,
555 );
556 assert_eq!(
557 (s.logical, s.physical, s.name),
558 (8, 4, "Intel Core i7-8700")
559 );
560 assert_eq!(s.raw_name, Some("Intel(R) Core(TM) i7-8700 CPU @ 3.20GHz"));
561 let s = facts_with(0, Some(99), None, None, Vendor::Arm);
562 assert_eq!((s.logical, s.physical), (1, 1));
563 assert_eq!(s.name, format!("ARM {}", arch().name()));
564 assert_eq!(
565 facts_with(4, None, Some(" "), None, Vendor::Unknown).name,
566 "unknown"
567 );
568 assert_eq!(
569 facts_with(4, None, None, Some("Cortex-A76"), Vendor::Arm).name,
570 "Cortex-A76"
571 );
572 }
573
574 #[test]
575 fn test_cpu_counts_and_load_live() {
576 let c = count();
577 assert!(c.packages >= 1 && c.packages <= c.physical);
578 assert!(c.online >= 1 && c.online <= c.logical);
579 if let Some(load) = load().unwrap() {
580 assert!(load.one >= 0.0 && load.five >= 0.0 && load.fifteen >= 0.0);
581 }
582 let f = frequency();
583 if let (Some(b), Some(m)) = (f.base, f.max) {
584 assert!(b.0 > 0 && m.0 > 0);
585 }
586 let _ = current_frequency().unwrap();
587 let _ = quota().unwrap();
588 let _ = pressure().unwrap();
589 }
590
591 #[test]
592 fn test_cpu_load_display_and_cleaning() {
593 let l = Load::new(2.149, f32::NAN, -1.0);
594 assert_eq!(l.to_string(), "2.15 0.00 0.00");
595 assert!(l.per_cpu().one <= l.one);
596 }
597
598 #[test]
599 fn test_cpu_packages_clamped() {
600 let s = build(crate::sys::CpuFacts {
601 logical: 8,
602 physical: Some(4),
603 packages: Some(9),
604 raw_name: None,
605 name: None,
606 vendor: Vendor::Amd,
607 });
608 assert_eq!((s.packages, s.physical_exact), (4, true));
609 assert!(!facts_with(8, None, None, None, Vendor::Amd).physical_exact);
610 }
611
612 #[test]
613 fn test_cpu_arch_names_and_bitness() {
614 assert_eq!(Arch::X86_64.name(), "x86_64");
615 assert!(Arch::X86_64.is_64bit() && !Arch::X86.is_64bit() && !Arch::Arm.is_64bit());
616 assert_eq!(arch().name(), std::env::consts::ARCH);
617 }
618}