use sysinfo::System;
#[derive(Debug, Clone)]
pub struct SystemResources {
pub cpu_cores: usize,
pub cpu_threads: usize,
pub total_memory_mb: u64,
pub available_memory_mb: u64,
}
impl SystemResources {
pub fn detect() -> Self {
let mut sys = System::new_all();
sys.refresh_all();
Self {
cpu_cores: num_cpus::get_physical(),
cpu_threads: num_cpus::get(),
total_memory_mb: sys.total_memory() / 1024 / 1024,
available_memory_mb: sys.available_memory() / 1024 / 1024,
}
}
pub fn resource_tier(&self) -> ResourceTier {
match (self.cpu_cores, self.total_memory_mb) {
(cores, mem) if cores >= 8 && mem >= 16000 => ResourceTier::High,
(cores, mem) if cores >= 4 && mem >= 8000 => ResourceTier::Medium,
_ => ResourceTier::Low,
}
}
pub fn tier_description(&self) -> &'static str {
match self.resource_tier() {
ResourceTier::High => "高性能",
ResourceTier::Medium => "标准配置",
ResourceTier::Low => "基础配置",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResourceTier {
Low,
Medium,
High,
}
impl ResourceTier {
pub fn as_str(&self) -> &'static str {
match self {
ResourceTier::Low => "Low",
ResourceTier::Medium => "Medium",
ResourceTier::High => "High",
}
}
}
impl std::fmt::Display for ResourceTier {
fn fmt(
&self,
f: &mut std::fmt::Formatter<'_>,
) -> std::fmt::Result {
write!(f, "{}", self.as_str())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_system_resources_detect() {
let resources = SystemResources::detect();
assert!(resources.cpu_cores > 0, "CPU核心数应该大于0");
assert!(resources.cpu_threads > 0, "CPU线程数应该大于0");
assert!(resources.total_memory_mb > 0, "总内存应该大于0");
assert!(
resources.cpu_threads >= resources.cpu_cores,
"CPU线程数应该大于等于核心数"
);
}
#[test]
fn test_resource_tier() {
let low_resources = SystemResources {
cpu_cores: 2,
cpu_threads: 2,
total_memory_mb: 4096,
available_memory_mb: 2048,
};
assert_eq!(low_resources.resource_tier(), ResourceTier::Low);
let medium_resources = SystemResources {
cpu_cores: 4,
cpu_threads: 8,
total_memory_mb: 8192,
available_memory_mb: 4096,
};
assert_eq!(medium_resources.resource_tier(), ResourceTier::Medium);
let high_resources = SystemResources {
cpu_cores: 8,
cpu_threads: 16,
total_memory_mb: 16384,
available_memory_mb: 8192,
};
assert_eq!(high_resources.resource_tier(), ResourceTier::High);
}
#[test]
fn test_tier_description() {
let resources = SystemResources::detect();
let description = resources.tier_description();
assert!(["高性能", "标准配置", "基础配置"].contains(&description));
}
}