Skip to main content

sys_lib/cpu/
mod.rs

1//! The processor: architecture and bitness, name and vendor, the counts
2//! (cores, hardware threads, sockets, and what this process may use), the
3//! frequency, usage, load, pressure, and instruction-set features.
4//!
5//! ```
6//! use sys_lib as sys;
7//!
8//! println!("{} ({:?}, {})", sys::cpu::name(), sys::cpu::vendor(), sys::cpu::arch().name());
9//! println!("{} cores, {} threads, {} usable here", sys::cpu::physical(), sys::cpu::logical(), sys::cpu::available());
10//! // Size a worker pool by what the container allows, not by the host.
11//! let workers = sys::cpu::available();
12//! # let _ = workers;
13//! ```
14
15use 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/// A processor architecture.
33#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
34#[non_exhaustive]
35pub enum Arch {
36    /// x86-64.
37    X86_64,
38    /// 32-bit x86.
39    X86,
40    /// 64-bit ARM.
41    Aarch64,
42    /// 32-bit ARM.
43    Arm,
44    /// 64-bit RISC-V.
45    Riscv64,
46    /// 64-bit PowerPC.
47    Powerpc64,
48    /// IBM Z.
49    S390x,
50    /// 64-bit LoongArch.
51    Loongarch64,
52    /// 32-bit WebAssembly.
53    Wasm32,
54    /// Anything else.
55    Other,
56}
57
58impl Arch {
59    /// The name rustc uses: `"x86_64"`, `"aarch64"`.
60    ///
61    /// ```
62    /// assert_eq!(sys_lib::cpu::Arch::Aarch64.name(), "aarch64");
63    /// ```
64    #[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    /// Whether the architecture is 64-bit.
81    ///
82    /// ```
83    /// // The program's own bitness, as a compile-time constant:
84    /// const BUILD_IS_64: bool = sys_lib::cpu::arch().is_64bit();
85    /// # let _ = BUILD_IS_64;
86    /// ```
87    #[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/// The architecture this program was compiled for.
102#[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/// Whether the **processor** is 64-bit. A 32-bit program on a 64-bit machine
128/// still sees `true` (D-024); the program's own bitness is
129/// `cpu::arch().is_64bit()`.
130///
131/// ```
132/// assert_ne!(sys_lib::cpu::is_64bit(), sys_lib::cpu::is_32bit());
133/// ```
134#[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/// Whether the processor is 32-bit only.
141#[must_use]
142pub fn is_32bit() -> bool {
143    !is_64bit()
144}
145
146/// The hardware's architecture, which differs from [`arch`] under Rosetta 2,
147/// WOW64, and ARM64 emulation.
148///
149/// ```
150/// println!("{} on {}", sys_lib::cpu::arch().name(), sys_lib::cpu::native_arch().name());
151/// ```
152#[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/// Whether this process runs under emulation: Rosetta 2, WOW64, or ARM64
159/// emulation (E-88, E-89).
160#[must_use]
161pub fn is_translated() -> bool {
162    native_arch() != arch()
163}
164
165/// A CPU designer or manufacturer.
166#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
167#[non_exhaustive]
168pub enum Vendor {
169    /// Intel.
170    Intel,
171    /// AMD.
172    Amd,
173    /// Apple.
174    Apple,
175    /// Arm (Cortex and Neoverse cores).
176    Arm,
177    /// Qualcomm.
178    Qualcomm,
179    /// Ampere Computing.
180    Ampere,
181    /// NVIDIA.
182    Nvidia,
183    /// Samsung.
184    Samsung,
185    /// MediaTek.
186    Mediatek,
187    /// Hygon.
188    Hygon,
189    /// Zhaoxin and VIA (Centaur).
190    Zhaoxin,
191    /// Broadcom.
192    Broadcom,
193    /// Marvell (formerly Cavium).
194    Marvell,
195    /// Fujitsu.
196    Fujitsu,
197    /// HiSilicon.
198    HiSilicon,
199    /// Microsoft (Azure Cobalt).
200    Microsoft,
201    /// Not known.
202    #[default]
203    Unknown,
204}
205
206impl Vendor {
207    /// The vendor's name: "Intel", "AMD", "ARM".
208    #[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
232// The static facts are cached apart, so a call reads only its own source: the
233// count is one small file or call, the cores a topology walk, the name the
234// brand string (D-101). One cache for all three made `logical()` pay for
235// `/proc/cpuinfo` on its first call.
236
237/// Cores and packages, held between 1 and the count.
238struct Layout {
239    physical: usize,
240    physical_exact: bool,
241    packages: usize,
242}
243
244/// The names and the vendor.
245struct 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/// Configured hardware threads: the right size for per-CPU arrays. A static
302/// fact (E-15: present CPUs, not the `possible` count VMs inflate). Windows
303/// counts every processor group (FR-12). At least 1.
304#[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/// Physical cores; [`logical`] when the topology is hidden (E-18). Always
311/// between 1 and `logical()`.
312#[must_use]
313pub fn physical() -> usize {
314    layout().physical
315}
316
317/// The CPUs this process may use right now: the affinity mask, intersected
318/// with the cgroup cpuset, then limited by the cgroup CPU quota (Linux), or the
319/// group affinity and the job object's CPU rate (Windows). Size worker pools by
320/// this. A live reading: affinity, hot-plug, and quotas change. Always between
321/// 1 and `logical()`.
322#[must_use]
323pub fn available() -> usize {
324    crate::sys::cpu_available(logical()).clamp(1, logical())
325}
326
327/// The cleaned product name: "AMD Ryzen 9 7950X", "Apple M2 Pro",
328/// "Cortex-A76 + Cortex-A55". Never empty: falls back to the vendor and
329/// architecture ("ARM aarch64"), then "unknown".
330#[must_use]
331pub fn name() -> &'static str {
332    identity().name
333}
334
335/// The name exactly as the OS reports it, for support output; `None` where the
336/// OS reports no brand string (most ARM Linux systems).
337#[must_use]
338pub fn raw_name() -> Option<&'static str> {
339    identity().raw_name
340}
341
342/// The vendor.
343#[must_use]
344pub fn vendor() -> Vendor {
345    identity().vendor
346}
347
348/// Processor packages (sockets): a static fact, 1 when the OS does not say.
349/// Always between 1 and `physical()`.
350#[must_use]
351pub fn packages() -> usize {
352    layout().packages
353}
354
355/// The CPUs online now, which hot-plug changes; between 1 and `logical()`.
356/// Linux: `/sys/devices/system/cpu/online`; macOS: `hw.activecpu`; Windows:
357/// the active processors across every processor group.
358#[must_use]
359pub fn online() -> usize {
360    crate::sys::cpu_online(logical()).clamp(1, logical())
361}
362
363/// Every count at once, with whether `physical` is exact.
364#[derive(Clone, Copy, PartialEq, Eq, Debug)]
365#[non_exhaustive]
366pub struct Counts {
367    /// [`logical`].
368    pub logical: usize,
369    /// [`physical`].
370    pub physical: usize,
371    /// [`packages`].
372    pub packages: usize,
373    /// [`available`], read now.
374    pub available: usize,
375    /// [`online`], read now.
376    pub online: usize,
377    /// False when the topology was hidden and `physical` fell back to
378    /// `logical` (E-18).
379    pub physical_exact: bool,
380}
381
382/// Every count at once; `available` and `online` are read now.
383///
384/// ```
385/// let c = sys_lib::cpu::count();
386/// assert!(c.available <= c.logical && c.physical <= c.logical);
387/// ```
388#[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/// A CPU quota: how much CPU time this process may use, in CPUs.
402#[derive(Clone, Copy, PartialEq, Debug)]
403#[non_exhaustive]
404pub struct CpuQuota {
405    /// The quota in CPUs: 1.5 is one and a half CPUs' worth of time.
406    pub cpus: f32,
407    /// Where it came from.
408    pub source: LimitSource,
409}
410
411/// The CPU quota on this process, or `None` when there is none. Linux: the
412/// smallest cgroup v2 `cpu.max` over the cgroup and its ancestors, or cgroup
413/// v1's `cpu.cfs_quota_us` over `cpu.cfs_period_us`. Windows: the job object's
414/// CPU rate cap. macOS: `None`. [`available`] already applies it, rounded up.
415///
416/// ```
417/// if let Some(q) = sys_lib::cpu::quota()? {
418///     println!("CPU quota {:.1} from {:?}", q.cpus, q.source);
419/// }
420/// # Ok::<(), sys_lib::Error>(())
421/// ```
422///
423/// # Errors
424///
425/// `Malformed` when a quota file does not parse; `Os` when the job-object
426/// query fails.
427pub fn quota() -> Result<Option<CpuQuota>> {
428    crate::sys::cpu_quota()
429}
430
431/// The base and maximum clock frequency.
432#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
433#[non_exhaustive]
434pub struct Frequency {
435    /// The base (nominal) frequency, when reported.
436    pub base: Option<Mhz>,
437    /// The maximum (boost) frequency, when reported.
438    pub max: Option<Mhz>,
439}
440
441/// The base and maximum frequency: a static fact. Apple silicon reports
442/// neither. There is no "total frequency": a sum of per-core frequencies means
443/// nothing.
444///
445/// ```
446/// if let Some(max) = sys_lib::cpu::frequency().max { println!("up to {max}"); }
447/// ```
448#[must_use]
449pub fn frequency() -> &'static Frequency {
450    static FREQUENCY: OnceLock<Frequency> = OnceLock::new();
451    FREQUENCY.get_or_init(crate::sys::frequency)
452}
453
454/// The current frequency, averaged over the online CPUs. `None` where the OS
455/// does not report it (macOS).
456///
457/// # Errors
458///
459/// `Malformed` when a frequency file does not parse; `Os` when the power query
460/// fails.
461pub fn current_frequency() -> Result<Option<Mhz>> {
462    crate::sys::current_frequency()
463}
464
465/// The load average: how many programs were running or waiting for a CPU, on
466/// average, over the last 1, 5, and 15 minutes.
467///
468/// Compare it with the number of CPUs, or use [`per_cpu`](Load::per_cpu):
469/// under 1.0 per CPU there was spare capacity, over 1.0 programs were queueing.
470/// On Linux it also counts programs waiting on disk, so high load with low CPU
471/// usage points at storage.
472#[derive(Clone, Copy, PartialEq, Debug)]
473#[non_exhaustive]
474pub struct Load {
475    /// The last minute.
476    pub one: f32,
477    /// The last 5 minutes.
478    pub five: f32,
479    /// The last 15 minutes.
480    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    /// Divided by [`logical`]: 1.0 means every CPU had work.
494    ///
495    /// ```
496    /// if let Some(load) = sys_lib::cpu::load()? {
497    ///     if load.per_cpu().one > 1.0 { /* programs are queueing for a CPU */ }
498    /// }
499    /// # Ok::<(), sys_lib::Error>(())
500    /// ```
501    #[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
514/// The load average, or `None` on Windows, which keeps none (nothing is
515/// simulated). Inside a container it is the host's (with LXCFS, the
516/// container's).
517///
518/// ```
519/// match sys_lib::cpu::load()? {
520///     Some(load) => println!("load {load} ({:.2} per CPU)", load.per_cpu().one),
521///     None => println!("this OS keeps no load average"),
522/// }
523/// # Ok::<(), sys_lib::Error>(())
524/// ```
525///
526/// # Errors
527///
528/// `Malformed` when `/proc/loadavg` does not parse.
529pub fn load() -> Result<Option<Load>> {
530    crate::sys::load()
531}
532
533/// How much runnable work waited for a CPU over the last 10, 60, and 300
534/// seconds ([`Pressure`]): the direct form of what the load average
535/// approximates. Linux: the cgroup's `cpu.pressure`, else `/proc/pressure/cpu`;
536/// `None` on kernels without pressure-stall information. macOS and Windows
537/// have no stall measure: `None`.
538///
539/// # Errors
540///
541/// `Malformed` when the kernel's file does not parse.
542pub fn pressure() -> Result<Option<Pressure>> {
543    crate::sys::cpu_pressure()
544}
545
546#[cfg(test)]
547mod tests {
548    use super::*;
549
550    /// Every static fact for one set of platform answers.
551    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        // 0 stands for "the OS did not say" in these tests.
587        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}