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 usage;
22
23pub use features::{Feature, Features, X86Level, features, has, x86_level};
24pub(crate) use usage::States;
25pub use usage::{DEFAULT_WINDOW, Sampler, Times, Usage, free, times, usage, usage_over, used};
26
27/// A processor architecture.
28#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
29#[non_exhaustive]
30pub enum Arch {
31    /// x86-64.
32    X86_64,
33    /// 32-bit x86.
34    X86,
35    /// 64-bit ARM.
36    Aarch64,
37    /// 32-bit ARM.
38    Arm,
39    /// 64-bit RISC-V.
40    Riscv64,
41    /// 64-bit PowerPC.
42    Powerpc64,
43    /// IBM Z.
44    S390x,
45    /// 64-bit LoongArch.
46    Loongarch64,
47    /// 32-bit WebAssembly.
48    Wasm32,
49    /// Anything else.
50    Other,
51}
52
53impl Arch {
54    /// The name rustc uses: `"x86_64"`, `"aarch64"`.
55    ///
56    /// ```
57    /// assert_eq!(sys_lib::cpu::Arch::Aarch64.name(), "aarch64");
58    /// ```
59    #[must_use]
60    pub const fn name(self) -> &'static str {
61        match self {
62            Self::X86_64 => "x86_64",
63            Self::X86 => "x86",
64            Self::Aarch64 => "aarch64",
65            Self::Arm => "arm",
66            Self::Riscv64 => "riscv64",
67            Self::Powerpc64 => "powerpc64",
68            Self::S390x => "s390x",
69            Self::Loongarch64 => "loongarch64",
70            Self::Wasm32 => "wasm32",
71            Self::Other => "other",
72        }
73    }
74
75    /// Whether the architecture is 64-bit.
76    ///
77    /// ```
78    /// // The program's own bitness, as a compile-time constant:
79    /// const BUILD_IS_64: bool = sys_lib::cpu::arch().is_64bit();
80    /// # let _ = BUILD_IS_64;
81    /// ```
82    #[must_use]
83    pub const fn is_64bit(self) -> bool {
84        matches!(
85            self,
86            Self::X86_64
87                | Self::Aarch64
88                | Self::Riscv64
89                | Self::Powerpc64
90                | Self::S390x
91                | Self::Loongarch64
92        )
93    }
94}
95
96/// The architecture this program was compiled for.
97#[must_use]
98pub const fn arch() -> Arch {
99    if cfg!(target_arch = "x86_64") {
100        Arch::X86_64
101    } else if cfg!(target_arch = "x86") {
102        Arch::X86
103    } else if cfg!(target_arch = "aarch64") {
104        Arch::Aarch64
105    } else if cfg!(target_arch = "arm") {
106        Arch::Arm
107    } else if cfg!(target_arch = "riscv64") {
108        Arch::Riscv64
109    } else if cfg!(target_arch = "powerpc64") {
110        Arch::Powerpc64
111    } else if cfg!(target_arch = "s390x") {
112        Arch::S390x
113    } else if cfg!(target_arch = "loongarch64") {
114        Arch::Loongarch64
115    } else if cfg!(target_arch = "wasm32") {
116        Arch::Wasm32
117    } else {
118        Arch::Other
119    }
120}
121
122/// Whether the **processor** is 64-bit. A 32-bit program on a 64-bit machine
123/// still sees `true` (D-024); the program's own bitness is
124/// `cpu::arch().is_64bit()`.
125///
126/// ```
127/// assert_ne!(sys_lib::cpu::is_64bit(), sys_lib::cpu::is_32bit());
128/// ```
129#[must_use]
130pub fn is_64bit() -> bool {
131    static IS_64: OnceLock<bool> = OnceLock::new();
132    *IS_64.get_or_init(crate::sys::processor_is_64bit)
133}
134
135/// Whether the processor is 32-bit only.
136#[must_use]
137pub fn is_32bit() -> bool {
138    !is_64bit()
139}
140
141/// A CPU designer or manufacturer.
142#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
143#[non_exhaustive]
144pub enum Vendor {
145    /// Intel.
146    Intel,
147    /// AMD.
148    Amd,
149    /// Apple.
150    Apple,
151    /// Arm (Cortex and Neoverse cores).
152    Arm,
153    /// Qualcomm.
154    Qualcomm,
155    /// Ampere Computing.
156    Ampere,
157    /// NVIDIA.
158    Nvidia,
159    /// Samsung.
160    Samsung,
161    /// MediaTek.
162    Mediatek,
163    /// Hygon.
164    Hygon,
165    /// Zhaoxin and VIA (Centaur).
166    Zhaoxin,
167    /// Broadcom.
168    Broadcom,
169    /// Marvell (formerly Cavium).
170    Marvell,
171    /// Fujitsu.
172    Fujitsu,
173    /// HiSilicon.
174    HiSilicon,
175    /// Microsoft (Azure Cobalt).
176    Microsoft,
177    /// Not known.
178    #[default]
179    Unknown,
180}
181
182impl Vendor {
183    /// The vendor's name: "Intel", "AMD", "ARM".
184    #[must_use]
185    pub const fn name(self) -> &'static str {
186        match self {
187            Self::Intel => "Intel",
188            Self::Amd => "AMD",
189            Self::Apple => "Apple",
190            Self::Arm => "ARM",
191            Self::Qualcomm => "Qualcomm",
192            Self::Ampere => "Ampere",
193            Self::Nvidia => "NVIDIA",
194            Self::Samsung => "Samsung",
195            Self::Mediatek => "MediaTek",
196            Self::Hygon => "Hygon",
197            Self::Zhaoxin => "Zhaoxin",
198            Self::Broadcom => "Broadcom",
199            Self::Marvell => "Marvell",
200            Self::Fujitsu => "Fujitsu",
201            Self::HiSilicon => "HiSilicon",
202            Self::Microsoft => "Microsoft",
203            Self::Unknown => "unknown",
204        }
205    }
206}
207
208struct Static {
209    logical: usize,
210    physical: usize,
211    physical_exact: bool,
212    packages: usize,
213    name: &'static str,
214    raw_name: Option<&'static str>,
215    vendor: Vendor,
216}
217
218fn facts() -> &'static Static {
219    static FACTS: OnceLock<Static> = OnceLock::new();
220    FACTS.get_or_init(|| build(crate::sys::cpu()))
221}
222
223fn build(f: crate::sys::CpuFacts) -> Static {
224    let logical = f.logical.max(1);
225    let physical = f.physical.unwrap_or(logical).clamp(1, logical);
226    let packages = f.packages.unwrap_or(1).clamp(1, physical);
227    let name = f
228        .name
229        .or_else(|| f.raw_name.as_deref().map(cpu_name::clean))
230        .filter(|n| !n.is_empty())
231        .unwrap_or_else(|| match f.vendor {
232            Vendor::Unknown => "unknown".to_owned(),
233            v => format!("{} {}", v.name(), arch().name()),
234        });
235    Static {
236        logical,
237        physical,
238        physical_exact: f.physical.is_some(),
239        packages,
240        name: keep(name),
241        raw_name: f.raw_name.filter(|n| !n.trim().is_empty()).map(keep),
242        vendor: f.vendor,
243    }
244}
245
246/// Configured hardware threads: the right size for per-CPU arrays. A static
247/// fact (E-15: present CPUs, not the `possible` count VMs inflate). Windows
248/// counts every processor group (FR-12). At least 1.
249#[must_use]
250pub fn logical() -> usize {
251    facts().logical
252}
253
254/// Physical cores; [`logical`] when the topology is hidden (E-18). Always
255/// between 1 and `logical()`.
256#[must_use]
257pub fn physical() -> usize {
258    facts().physical
259}
260
261/// The CPUs this process may use right now: the affinity mask, intersected
262/// with the cgroup cpuset, then limited by the cgroup CPU quota (Linux), or the
263/// group affinity and the job object's CPU rate (Windows). Size worker pools by
264/// this. A live reading: affinity, hot-plug, and quotas change. Always between
265/// 1 and `logical()`.
266#[must_use]
267pub fn available() -> usize {
268    crate::sys::cpu_available(logical()).clamp(1, logical())
269}
270
271/// The cleaned product name: "AMD Ryzen 9 7950X", "Apple M2 Pro",
272/// "Cortex-A76 + Cortex-A55". Never empty: falls back to the vendor and
273/// architecture ("ARM aarch64"), then "unknown".
274#[must_use]
275pub fn name() -> &'static str {
276    facts().name
277}
278
279/// The name exactly as the OS reports it, for support output; `None` where the
280/// OS reports no brand string (most ARM Linux systems).
281#[must_use]
282pub fn raw_name() -> Option<&'static str> {
283    facts().raw_name
284}
285
286/// The vendor.
287#[must_use]
288pub fn vendor() -> Vendor {
289    facts().vendor
290}
291
292/// Processor packages (sockets): a static fact, 1 when the OS does not say.
293/// Always between 1 and `physical()`.
294#[must_use]
295pub fn packages() -> usize {
296    facts().packages
297}
298
299/// The CPUs online now, which hot-plug changes; between 1 and `logical()`.
300/// Linux: `/sys/devices/system/cpu/online`; macOS: `hw.activecpu`; Windows:
301/// the active processors across every processor group.
302#[must_use]
303pub fn online() -> usize {
304    crate::sys::cpu_online(logical()).clamp(1, logical())
305}
306
307/// Every count at once, with whether `physical` is exact.
308#[derive(Clone, Copy, PartialEq, Eq, Debug)]
309#[non_exhaustive]
310pub struct Counts {
311    /// [`logical`].
312    pub logical: usize,
313    /// [`physical`].
314    pub physical: usize,
315    /// [`packages`].
316    pub packages: usize,
317    /// [`available`], read now.
318    pub available: usize,
319    /// [`online`], read now.
320    pub online: usize,
321    /// False when the topology was hidden and `physical` fell back to
322    /// `logical` (E-18).
323    pub physical_exact: bool,
324}
325
326/// Every count at once; `available` and `online` are read now.
327///
328/// ```
329/// let c = sys_lib::cpu::count();
330/// assert!(c.available <= c.logical && c.physical <= c.logical);
331/// ```
332#[must_use]
333pub fn count() -> Counts {
334    let f = facts();
335    Counts {
336        logical: f.logical,
337        physical: f.physical,
338        packages: f.packages,
339        available: available(),
340        online: online(),
341        physical_exact: f.physical_exact,
342    }
343}
344
345/// A CPU quota: how much CPU time this process may use, in CPUs.
346#[derive(Clone, Copy, PartialEq, Debug)]
347#[non_exhaustive]
348pub struct CpuQuota {
349    /// The quota in CPUs: 1.5 is one and a half CPUs' worth of time.
350    pub cpus: f32,
351    /// Where it came from.
352    pub source: LimitSource,
353}
354
355/// The CPU quota on this process, or `None` when there is none. Linux: the
356/// smallest cgroup v2 `cpu.max` over the cgroup and its ancestors, or cgroup
357/// v1's `cpu.cfs_quota_us` over `cpu.cfs_period_us`. Windows: the job object's
358/// CPU rate cap. macOS: `None`. [`available`] already applies it, rounded up.
359///
360/// ```
361/// if let Some(q) = sys_lib::cpu::quota()? {
362///     println!("CPU quota {:.1} from {:?}", q.cpus, q.source);
363/// }
364/// # Ok::<(), sys_lib::Error>(())
365/// ```
366///
367/// # Errors
368///
369/// `Malformed` when a quota file does not parse; `Os` when the job-object
370/// query fails.
371pub fn quota() -> Result<Option<CpuQuota>> {
372    crate::sys::cpu_quota()
373}
374
375/// The base and maximum clock frequency.
376#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
377#[non_exhaustive]
378pub struct Frequency {
379    /// The base (nominal) frequency, when reported.
380    pub base: Option<Mhz>,
381    /// The maximum (boost) frequency, when reported.
382    pub max: Option<Mhz>,
383}
384
385/// The base and maximum frequency: a static fact. Apple silicon reports
386/// neither. There is no "total frequency": a sum of per-core frequencies means
387/// nothing.
388///
389/// ```
390/// if let Some(max) = sys_lib::cpu::frequency().max { println!("up to {max}"); }
391/// ```
392#[must_use]
393pub fn frequency() -> &'static Frequency {
394    static FREQUENCY: OnceLock<Frequency> = OnceLock::new();
395    FREQUENCY.get_or_init(crate::sys::frequency)
396}
397
398/// The current frequency, averaged over the online CPUs. `None` where the OS
399/// does not report it (macOS).
400///
401/// # Errors
402///
403/// `Malformed` when a frequency file does not parse; `Os` when the power query
404/// fails.
405pub fn current_frequency() -> Result<Option<Mhz>> {
406    crate::sys::current_frequency()
407}
408
409/// The load average: how many programs were running or waiting for a CPU, on
410/// average, over the last 1, 5, and 15 minutes.
411///
412/// Compare it with the number of CPUs, or use [`per_cpu`](Load::per_cpu):
413/// under 1.0 per CPU there was spare capacity, over 1.0 programs were queueing.
414/// On Linux it also counts programs waiting on disk, so high load with low CPU
415/// usage points at storage.
416#[derive(Clone, Copy, PartialEq, Debug)]
417#[non_exhaustive]
418pub struct Load {
419    /// The last minute.
420    pub one: f32,
421    /// The last 5 minutes.
422    pub five: f32,
423    /// The last 15 minutes.
424    pub fifteen: f32,
425}
426
427impl Load {
428    pub(crate) fn new(one: f32, five: f32, fifteen: f32) -> Load {
429        let clean = |v: f32| if v.is_finite() { v.max(0.0) } else { 0.0 };
430        Load {
431            one: clean(one),
432            five: clean(five),
433            fifteen: clean(fifteen),
434        }
435    }
436
437    /// Divided by [`logical`]: 1.0 means every CPU had work.
438    ///
439    /// ```
440    /// if let Some(load) = sys_lib::cpu::load()? {
441    ///     if load.per_cpu().one > 1.0 { /* programs are queueing for a CPU */ }
442    /// }
443    /// # Ok::<(), sys_lib::Error>(())
444    /// ```
445    #[must_use]
446    pub fn per_cpu(&self) -> Load {
447        let n = logical() as f32;
448        Load::new(self.one / n, self.five / n, self.fifteen / n)
449    }
450}
451
452impl fmt::Display for Load {
453    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
454        write!(f, "{:.2} {:.2} {:.2}", self.one, self.five, self.fifteen)
455    }
456}
457
458/// The load average, or `None` on Windows, which keeps none (nothing is
459/// simulated). Inside a container it is the host's (with LXCFS, the
460/// container's).
461///
462/// ```
463/// match sys_lib::cpu::load()? {
464///     Some(load) => println!("load {load} ({:.2} per CPU)", load.per_cpu().one),
465///     None => println!("this OS keeps no load average"),
466/// }
467/// # Ok::<(), sys_lib::Error>(())
468/// ```
469///
470/// # Errors
471///
472/// `Malformed` when `/proc/loadavg` does not parse.
473pub fn load() -> Result<Option<Load>> {
474    crate::sys::load()
475}
476
477/// How much runnable work waited for a CPU over the last 10, 60, and 300
478/// seconds ([`Pressure`]): the direct form of what the load average
479/// approximates. Linux: the cgroup's `cpu.pressure`, else `/proc/pressure/cpu`;
480/// `None` on kernels without pressure-stall information. macOS and Windows
481/// have no stall measure: `None`.
482///
483/// # Errors
484///
485/// `Malformed` when the kernel's file does not parse.
486pub fn pressure() -> Result<Option<Pressure>> {
487    crate::sys::cpu_pressure()
488}
489
490#[cfg(test)]
491mod tests {
492    use super::*;
493
494    fn facts_with(
495        logical: usize,
496        physical: Option<usize>,
497        raw: Option<&str>,
498        name: Option<&str>,
499        vendor: Vendor,
500    ) -> Static {
501        build(crate::sys::CpuFacts {
502            logical,
503            physical,
504            packages: None,
505            raw_name: raw.map(str::to_owned),
506            name: name.map(str::to_owned),
507            vendor,
508        })
509    }
510
511    #[test]
512    fn test_cpu_counts_hold_their_invariants() {
513        assert!(physical() >= 1 && physical() <= logical());
514        let a = available();
515        assert!(a >= 1 && a <= logical());
516        assert_ne!(is_64bit(), is_32bit());
517        if arch().is_64bit() {
518            assert!(is_64bit());
519        }
520        assert!(!name().is_empty());
521    }
522
523    #[test]
524    fn test_cpu_build_cleans_and_falls_back() {
525        let s = facts_with(
526            8,
527            Some(4),
528            Some("Intel(R) Core(TM) i7-8700 CPU @ 3.20GHz"),
529            None,
530            Vendor::Intel,
531        );
532        assert_eq!(
533            (s.logical, s.physical, s.name),
534            (8, 4, "Intel Core i7-8700")
535        );
536        assert_eq!(s.raw_name, Some("Intel(R) Core(TM) i7-8700 CPU @ 3.20GHz"));
537        let s = facts_with(0, Some(99), None, None, Vendor::Arm);
538        assert_eq!((s.logical, s.physical), (1, 1));
539        assert_eq!(s.name, format!("ARM {}", arch().name()));
540        assert_eq!(
541            facts_with(4, None, Some("  "), None, Vendor::Unknown).name,
542            "unknown"
543        );
544        assert_eq!(
545            facts_with(4, None, None, Some("Cortex-A76"), Vendor::Arm).name,
546            "Cortex-A76"
547        );
548    }
549
550    #[test]
551    fn test_cpu_counts_and_load_live() {
552        let c = count();
553        assert!(c.packages >= 1 && c.packages <= c.physical);
554        assert!(c.online >= 1 && c.online <= c.logical);
555        if let Some(load) = load().unwrap() {
556            assert!(load.one >= 0.0 && load.five >= 0.0 && load.fifteen >= 0.0);
557        }
558        let f = frequency();
559        if let (Some(b), Some(m)) = (f.base, f.max) {
560            assert!(b.0 > 0 && m.0 > 0);
561        }
562        let _ = current_frequency().unwrap();
563        let _ = quota().unwrap();
564        let _ = pressure().unwrap();
565    }
566
567    #[test]
568    fn test_cpu_load_display_and_cleaning() {
569        let l = Load::new(2.149, f32::NAN, -1.0);
570        assert_eq!(l.to_string(), "2.15 0.00 0.00");
571        assert!(l.per_cpu().one <= l.one);
572    }
573
574    #[test]
575    fn test_cpu_packages_clamped() {
576        let s = build(crate::sys::CpuFacts {
577            logical: 8,
578            physical: Some(4),
579            packages: Some(9),
580            raw_name: None,
581            name: None,
582            vendor: Vendor::Amd,
583        });
584        assert_eq!((s.packages, s.physical_exact), (4, true));
585        assert!(!facts_with(8, None, None, None, Vendor::Amd).physical_exact);
586    }
587
588    #[test]
589    fn test_cpu_arch_names_and_bitness() {
590        assert_eq!(Arch::X86_64.name(), "x86_64");
591        assert!(Arch::X86_64.is_64bit() && !Arch::X86.is_64bit() && !Arch::Arm.is_64bit());
592        assert_eq!(arch().name(), std::env::consts::ARCH);
593    }
594}