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 Layout {
239 physical: usize,
240 physical_exact: bool,
241 packages: usize,
242}
243
244struct Identity {
246 name: &'static str,
247 raw_name: Option<&'static str>,
248 vendor: Vendor,
249}
250
251fn layout() -> &'static Layout {
252 static LAYOUT: OnceLock<Layout> = OnceLock::new();
253 LAYOUT.get_or_init(|| {
254 let (physical, packages) = crate::sys::cpu_counts();
255 layout_of(logical(), physical, packages)
256 })
257}
258
259fn identity() -> &'static Identity {
260 static IDENTITY: OnceLock<Identity> = OnceLock::new();
261 IDENTITY.get_or_init(|| identity_of(crate::sys::cpu_identity()))
262}
263
264fn logical_of(reported: Option<usize>) -> usize {
265 reported
266 .filter(|&n| n > 0)
267 .or_else(|| {
268 std::thread::available_parallelism()
269 .ok()
270 .map(std::num::NonZero::get)
271 })
272 .unwrap_or(1)
273}
274
275fn layout_of(logical: usize, physical: Option<usize>, packages: Option<usize>) -> Layout {
276 let logical = logical.max(1);
277 let cores = physical.unwrap_or(logical).clamp(1, logical);
278 Layout {
279 physical: cores,
280 physical_exact: physical.is_some(),
281 packages: packages.unwrap_or(1).clamp(1, cores),
282 }
283}
284
285fn identity_of(f: crate::sys::CpuIdentity) -> Identity {
286 let name = f
287 .name
288 .or_else(|| f.raw_name.as_deref().map(cpu_name::clean))
289 .filter(|n| !n.is_empty())
290 .unwrap_or_else(|| match f.vendor {
291 Vendor::Unknown => "unknown".to_owned(),
292 v => format!("{} {}", v.name(), arch().name()),
293 });
294 Identity {
295 name: keep(name),
296 raw_name: f.raw_name.filter(|n| !n.trim().is_empty()).map(keep),
297 vendor: f.vendor,
298 }
299}
300
301#[must_use]
305pub fn logical() -> usize {
306 static LOGICAL: OnceLock<usize> = OnceLock::new();
307 *LOGICAL.get_or_init(|| logical_of(crate::sys::cpu_logical()))
308}
309
310#[must_use]
313pub fn physical() -> usize {
314 layout().physical
315}
316
317#[must_use]
323pub fn available() -> usize {
324 crate::sys::cpu_available(logical()).clamp(1, logical())
325}
326
327#[must_use]
331pub fn name() -> &'static str {
332 identity().name
333}
334
335#[must_use]
338pub fn raw_name() -> Option<&'static str> {
339 identity().raw_name
340}
341
342#[must_use]
344pub fn vendor() -> Vendor {
345 identity().vendor
346}
347
348#[must_use]
351pub fn packages() -> usize {
352 layout().packages
353}
354
355#[must_use]
359pub fn online() -> usize {
360 crate::sys::cpu_online(logical()).clamp(1, logical())
361}
362
363#[derive(Clone, Copy, PartialEq, Eq, Debug)]
365#[non_exhaustive]
366pub struct Counts {
367 pub logical: usize,
369 pub physical: usize,
371 pub packages: usize,
373 pub available: usize,
375 pub online: usize,
377 pub physical_exact: bool,
380}
381
382#[must_use]
389pub fn count() -> Counts {
390 let l = layout();
391 Counts {
392 logical: logical(),
393 physical: l.physical,
394 packages: l.packages,
395 available: available(),
396 online: online(),
397 physical_exact: l.physical_exact,
398 }
399}
400
401#[derive(Clone, Copy, PartialEq, Debug)]
403#[non_exhaustive]
404pub struct CpuQuota {
405 pub cpus: f32,
407 pub source: LimitSource,
409}
410
411pub fn quota() -> Result<Option<CpuQuota>> {
428 crate::sys::cpu_quota()
429}
430
431#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
433#[non_exhaustive]
434pub struct Frequency {
435 pub base: Option<Mhz>,
437 pub max: Option<Mhz>,
439}
440
441#[must_use]
449pub fn frequency() -> &'static Frequency {
450 static FREQUENCY: OnceLock<Frequency> = OnceLock::new();
451 FREQUENCY.get_or_init(crate::sys::frequency)
452}
453
454pub fn current_frequency() -> Result<Option<Mhz>> {
462 crate::sys::current_frequency()
463}
464
465#[derive(Clone, Copy, PartialEq, Debug)]
473#[non_exhaustive]
474pub struct Load {
475 pub one: f32,
477 pub five: f32,
479 pub fifteen: f32,
481}
482
483impl Load {
484 pub(crate) fn new(one: f32, five: f32, fifteen: f32) -> Load {
485 let clean = |v: f32| if v.is_finite() { v.max(0.0) } else { 0.0 };
486 Load {
487 one: clean(one),
488 five: clean(five),
489 fifteen: clean(fifteen),
490 }
491 }
492
493 #[must_use]
502 pub fn per_cpu(&self) -> Load {
503 let n = logical() as f32;
504 Load::new(self.one / n, self.five / n, self.fifteen / n)
505 }
506}
507
508impl fmt::Display for Load {
509 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
510 write!(f, "{:.2} {:.2} {:.2}", self.one, self.five, self.fifteen)
511 }
512}
513
514pub fn load() -> Result<Option<Load>> {
530 crate::sys::load()
531}
532
533pub fn pressure() -> Result<Option<Pressure>> {
543 crate::sys::cpu_pressure()
544}
545
546#[cfg(test)]
547mod tests {
548 use super::*;
549
550 struct Static {
552 logical: usize,
553 physical: usize,
554 physical_exact: bool,
555 packages: usize,
556 name: &'static str,
557 raw_name: Option<&'static str>,
558 }
559
560 fn build(
561 logical: Option<usize>,
562 physical: Option<usize>,
563 packages: Option<usize>,
564 ident: crate::sys::CpuIdentity,
565 ) -> Static {
566 let logical = logical_of(logical);
567 let l = layout_of(logical, physical, packages);
568 let i = identity_of(ident);
569 Static {
570 logical,
571 physical: l.physical,
572 physical_exact: l.physical_exact,
573 packages: l.packages,
574 name: i.name,
575 raw_name: i.raw_name,
576 }
577 }
578
579 fn facts_with(
580 logical: usize,
581 physical: Option<usize>,
582 raw: Option<&str>,
583 name: Option<&str>,
584 vendor: Vendor,
585 ) -> Static {
586 let logical = (logical > 0).then_some(logical);
588 build(
589 logical,
590 physical,
591 None,
592 crate::sys::CpuIdentity {
593 raw_name: raw.map(str::to_owned),
594 name: name.map(str::to_owned),
595 vendor,
596 },
597 )
598 }
599
600 #[test]
601 fn test_cpu_counts_hold_their_invariants() {
602 assert!(physical() >= 1 && physical() <= logical());
603 let a = available();
604 assert!(a >= 1 && a <= logical());
605 assert_ne!(is_64bit(), is_32bit());
606 if arch().is_64bit() {
607 assert!(is_64bit());
608 }
609 assert!(!name().is_empty());
610 }
611
612 #[test]
613 fn test_cpu_build_cleans_and_falls_back() {
614 let s = facts_with(
615 8,
616 Some(4),
617 Some("Intel(R) Core(TM) i7-8700 CPU @ 3.20GHz"),
618 None,
619 Vendor::Intel,
620 );
621 assert_eq!(
622 (s.logical, s.physical, s.name),
623 (8, 4, "Intel Core i7-8700")
624 );
625 assert_eq!(s.raw_name, Some("Intel(R) Core(TM) i7-8700 CPU @ 3.20GHz"));
626 let s = build(
627 Some(1),
628 Some(99),
629 None,
630 crate::sys::CpuIdentity {
631 raw_name: None,
632 name: None,
633 vendor: Vendor::Arm,
634 },
635 );
636 assert_eq!((s.logical, s.physical), (1, 1));
637 assert_eq!(s.name, format!("ARM {}", arch().name()));
638 assert_eq!(
639 facts_with(4, None, Some(" "), None, Vendor::Unknown).name,
640 "unknown"
641 );
642 assert_eq!(
643 facts_with(4, None, None, Some("Cortex-A76"), Vendor::Arm).name,
644 "Cortex-A76"
645 );
646 }
647
648 #[test]
649 fn test_cpu_counts_and_load_live() {
650 let c = count();
651 assert!(c.packages >= 1 && c.packages <= c.physical);
652 assert!(c.online >= 1 && c.online <= c.logical);
653 if let Some(load) = load().unwrap() {
654 assert!(load.one >= 0.0 && load.five >= 0.0 && load.fifteen >= 0.0);
655 }
656 let f = frequency();
657 if let (Some(b), Some(m)) = (f.base, f.max) {
658 assert!(b.0 > 0 && m.0 > 0);
659 }
660 let _ = current_frequency().unwrap();
661 let _ = quota().unwrap();
662 let _ = pressure().unwrap();
663 }
664
665 #[test]
666 fn test_cpu_load_display_and_cleaning() {
667 let l = Load::new(2.149, f32::NAN, -1.0);
668 assert_eq!(l.to_string(), "2.15 0.00 0.00");
669 assert!(l.per_cpu().one <= l.one);
670 }
671
672 #[test]
673 fn test_cpu_packages_clamped() {
674 let s = build(
675 Some(8),
676 Some(4),
677 Some(9),
678 crate::sys::CpuIdentity {
679 raw_name: None,
680 name: None,
681 vendor: Vendor::Amd,
682 },
683 );
684 assert_eq!((s.packages, s.physical_exact), (4, true));
685 assert!(!facts_with(8, None, None, None, Vendor::Amd).physical_exact);
686 }
687
688 #[test]
689 fn test_cpu_arch_names_and_bitness() {
690 assert_eq!(Arch::X86_64.name(), "x86_64");
691 assert!(Arch::X86_64.is_64bit() && !Arch::X86.is_64bit() && !Arch::Arm.is_64bit());
692 assert_eq!(arch().name(), std::env::consts::ARCH);
693 }
694}