eryon_rt/types/
system.rs

1/*
2    Appellation: config <module>
3    Contrib: @FL03
4*/
5use std::sync::Arc;
6use sysinfo::System;
7
8/// Information about the system resources
9#[derive(Clone, Debug)]
10pub struct SystemInfo {
11    pub(crate) physical_core_count: usize,
12    pub(crate) sysinfo: Arc<System>,
13}
14
15impl SystemInfo {
16    /// Create a new SystemInfo by querying actual system resources
17    pub fn new() -> Self {
18        // get the number of physical cores
19        let physical_core_count = System::physical_core_count().unwrap_or(1);
20        let mut system = System::new_all();
21        system.refresh_all();
22
23        Self {
24            physical_core_count,
25            sysinfo: Arc::new(system),
26        }
27    }
28    /// returns the amount of free memory in bytes
29    pub fn free_memory(&self) -> u64 {
30        self.sysinfo.free_memory()
31    }
32    /// returns the number of cores in the system
33    pub fn get_cpu_cores(&self) -> usize {
34        self.physical_core_count
35    }
36    /// Get the current CPU load as a fraction (0.0 to 1.0)
37    pub fn get_cpu_usage(&self) -> f32 {
38        self.sysinfo.global_cpu_usage()
39    }
40    /// returns the amount of free memory in MB
41    pub fn get_free_memory_mb(&self) -> usize {
42        self.sysinfo.free_memory() as usize / 1024 / 1024
43    }
44    /// returns the normalized (0.0 to 1.0) memory usage
45    pub fn get_ram_memory_usage(&self) -> f32 {
46        self.sysinfo.used_memory() as f32 / self.sysinfo.total_memory() as f32
47    }
48    /// Get the current system load as a fraction (0.0 to 1.0)
49    pub fn get_current_load(&self) -> f32 {
50        // Return CPU usage as a proxy for system load
51        self.get_cpu_usage()
52    }
53    /// Get memory usage in bytes
54    pub fn memory_usage(&self) -> f32 {
55        self.free_memory() as f32 * self.get_ram_memory_usage()
56    }
57}
58
59impl Default for SystemInfo {
60    fn default() -> Self {
61        SystemInfo::new()
62    }
63}
64
65impl core::ops::Deref for SystemInfo {
66    type Target = System;
67
68    fn deref(&self) -> &Self::Target {
69        &self.sysinfo
70    }
71}
72
73impl core::fmt::Display for SystemInfo {
74    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
75        write!(
76            f,
77            "SystemInfo: \nCPU cores: {}, \nFree memory: {} MB",
78            self.get_cpu_cores(),
79            self.free_memory()
80        )
81    }
82}
83
84impl From<sysinfo::System> for SystemInfo {
85    fn from(system: sysinfo::System) -> Self {
86        Self {
87            sysinfo: Arc::new(system),
88            physical_core_count: sysinfo::System::physical_core_count().unwrap_or(1),
89        }
90    }
91}