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
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/// Configured hardware threads: the right size for per-CPU arrays. A static
271/// fact (E-15: present CPUs, not the `possible` count VMs inflate). Windows
272/// counts every processor group (FR-12). At least 1.
273#[must_use]
274pub fn logical() -> usize {
275    facts().logical
276}
277
278/// Physical cores; [`logical`] when the topology is hidden (E-18). Always
279/// between 1 and `logical()`.
280#[must_use]
281pub fn physical() -> usize {
282    facts().physical
283}
284
285/// The CPUs this process may use right now: the affinity mask, intersected
286/// with the cgroup cpuset, then limited by the cgroup CPU quota (Linux), or the
287/// group affinity and the job object's CPU rate (Windows). Size worker pools by
288/// this. A live reading: affinity, hot-plug, and quotas change. Always between
289/// 1 and `logical()`.
290#[must_use]
291pub fn available() -> usize {
292    crate::sys::cpu_available(logical()).clamp(1, logical())
293}
294
295/// The cleaned product name: "AMD Ryzen 9 7950X", "Apple M2 Pro",
296/// "Cortex-A76 + Cortex-A55". Never empty: falls back to the vendor and
297/// architecture ("ARM aarch64"), then "unknown".
298#[must_use]
299pub fn name() -> &'static str {
300    facts().name
301}
302
303/// The name exactly as the OS reports it, for support output; `None` where the
304/// OS reports no brand string (most ARM Linux systems).
305#[must_use]
306pub fn raw_name() -> Option<&'static str> {
307    facts().raw_name
308}
309
310/// The vendor.
311#[must_use]
312pub fn vendor() -> Vendor {
313    facts().vendor
314}
315
316/// Processor packages (sockets): a static fact, 1 when the OS does not say.
317/// Always between 1 and `physical()`.
318#[must_use]
319pub fn packages() -> usize {
320    facts().packages
321}
322
323/// The CPUs online now, which hot-plug changes; between 1 and `logical()`.
324/// Linux: `/sys/devices/system/cpu/online`; macOS: `hw.activecpu`; Windows:
325/// the active processors across every processor group.
326#[must_use]
327pub fn online() -> usize {
328    crate::sys::cpu_online(logical()).clamp(1, logical())
329}
330
331/// Every count at once, with whether `physical` is exact.
332#[derive(Clone, Copy, PartialEq, Eq, Debug)]
333#[non_exhaustive]
334pub struct Counts {
335    /// [`logical`].
336    pub logical: usize,
337    /// [`physical`].
338    pub physical: usize,
339    /// [`packages`].
340    pub packages: usize,
341    /// [`available`], read now.
342    pub available: usize,
343    /// [`online`], read now.
344    pub online: usize,
345    /// False when the topology was hidden and `physical` fell back to
346    /// `logical` (E-18).
347    pub physical_exact: bool,
348}
349
350/// Every count at once; `available` and `online` are read now.
351///
352/// ```
353/// let c = sys_lib::cpu::count();
354/// assert!(c.available <= c.logical && c.physical <= c.logical);
355/// ```
356#[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/// A CPU quota: how much CPU time this process may use, in CPUs.
370#[derive(Clone, Copy, PartialEq, Debug)]
371#[non_exhaustive]
372pub struct CpuQuota {
373    /// The quota in CPUs: 1.5 is one and a half CPUs' worth of time.
374    pub cpus: f32,
375    /// Where it came from.
376    pub source: LimitSource,
377}
378
379/// The CPU quota on this process, or `None` when there is none. Linux: the
380/// smallest cgroup v2 `cpu.max` over the cgroup and its ancestors, or cgroup
381/// v1's `cpu.cfs_quota_us` over `cpu.cfs_period_us`. Windows: the job object's
382/// CPU rate cap. macOS: `None`. [`available`] already applies it, rounded up.
383///
384/// ```
385/// if let Some(q) = sys_lib::cpu::quota()? {
386///     println!("CPU quota {:.1} from {:?}", q.cpus, q.source);
387/// }
388/// # Ok::<(), sys_lib::Error>(())
389/// ```
390///
391/// # Errors
392///
393/// `Malformed` when a quota file does not parse; `Os` when the job-object
394/// query fails.
395pub fn quota() -> Result<Option<CpuQuota>> {
396    crate::sys::cpu_quota()
397}
398
399/// The base and maximum clock frequency.
400#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
401#[non_exhaustive]
402pub struct Frequency {
403    /// The base (nominal) frequency, when reported.
404    pub base: Option<Mhz>,
405    /// The maximum (boost) frequency, when reported.
406    pub max: Option<Mhz>,
407}
408
409/// The base and maximum frequency: a static fact. Apple silicon reports
410/// neither. There is no "total frequency": a sum of per-core frequencies means
411/// nothing.
412///
413/// ```
414/// if let Some(max) = sys_lib::cpu::frequency().max { println!("up to {max}"); }
415/// ```
416#[must_use]
417pub fn frequency() -> &'static Frequency {
418    static FREQUENCY: OnceLock<Frequency> = OnceLock::new();
419    FREQUENCY.get_or_init(crate::sys::frequency)
420}
421
422/// The current frequency, averaged over the online CPUs. `None` where the OS
423/// does not report it (macOS).
424///
425/// # Errors
426///
427/// `Malformed` when a frequency file does not parse; `Os` when the power query
428/// fails.
429pub fn current_frequency() -> Result<Option<Mhz>> {
430    crate::sys::current_frequency()
431}
432
433/// The load average: how many programs were running or waiting for a CPU, on
434/// average, over the last 1, 5, and 15 minutes.
435///
436/// Compare it with the number of CPUs, or use [`per_cpu`](Load::per_cpu):
437/// under 1.0 per CPU there was spare capacity, over 1.0 programs were queueing.
438/// On Linux it also counts programs waiting on disk, so high load with low CPU
439/// usage points at storage.
440#[derive(Clone, Copy, PartialEq, Debug)]
441#[non_exhaustive]
442pub struct Load {
443    /// The last minute.
444    pub one: f32,
445    /// The last 5 minutes.
446    pub five: f32,
447    /// The last 15 minutes.
448    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    /// Divided by [`logical`]: 1.0 means every CPU had work.
462    ///
463    /// ```
464    /// if let Some(load) = sys_lib::cpu::load()? {
465    ///     if load.per_cpu().one > 1.0 { /* programs are queueing for a CPU */ }
466    /// }
467    /// # Ok::<(), sys_lib::Error>(())
468    /// ```
469    #[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
482/// The load average, or `None` on Windows, which keeps none (nothing is
483/// simulated). Inside a container it is the host's (with LXCFS, the
484/// container's).
485///
486/// ```
487/// match sys_lib::cpu::load()? {
488///     Some(load) => println!("load {load} ({:.2} per CPU)", load.per_cpu().one),
489///     None => println!("this OS keeps no load average"),
490/// }
491/// # Ok::<(), sys_lib::Error>(())
492/// ```
493///
494/// # Errors
495///
496/// `Malformed` when `/proc/loadavg` does not parse.
497pub fn load() -> Result<Option<Load>> {
498    crate::sys::load()
499}
500
501/// How much runnable work waited for a CPU over the last 10, 60, and 300
502/// seconds ([`Pressure`]): the direct form of what the load average
503/// approximates. Linux: the cgroup's `cpu.pressure`, else `/proc/pressure/cpu`;
504/// `None` on kernels without pressure-stall information. macOS and Windows
505/// have no stall measure: `None`.
506///
507/// # Errors
508///
509/// `Malformed` when the kernel's file does not parse.
510pub 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}