stats.rs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. use std::time::Instant;
  2. /// 单个 CPU 核心的时间统计
  3. #[derive(Debug, Default, Clone)]
  4. pub struct CpuTimes {
  5. pub user: u64, // 用户态时间
  6. pub nice: u64, // 低优先级进程时间
  7. pub system: u64, // 内核态时间
  8. pub idle: u64, // 空闲时间
  9. #[allow(dead_code)] // 这些字段用于完整的 CPU 时间统计,为未来功能预留
  10. pub iowait: u64, // I/O 等待时间
  11. #[allow(dead_code)] // 这些字段用于完整的 CPU 时间统计,为未来功能预留
  12. pub irq: u64, // 硬中断时间
  13. #[allow(dead_code)] // 这些字段用于完整的 CPU 时间统计,为未来功能预留
  14. pub softirq: u64, // 软中断时间
  15. pub total: u64, // 总时间
  16. }
  17. /// CPU 使用率分解
  18. #[derive(Debug, Default, Clone)]
  19. pub struct CpuUsageBreakdown {
  20. pub user_percent: f32, // 用户态使用率百分比
  21. pub nice_percent: f32, // 低优先级进程使用率百分比
  22. pub system_percent: f32, // 内核态使用率百分比
  23. pub total_percent: f32, // 总使用率百分比
  24. }
  25. /// 多核 CPU 统计信息
  26. #[derive(Debug, Clone)]
  27. pub struct CpuStats {
  28. pub overall: CpuUsageBreakdown, // 总体 CPU 使用率
  29. pub per_core: Vec<CpuUsageBreakdown>, // 每个 CPU 核心的使用率
  30. pub core_count: usize, // CPU 核心数量
  31. }
  32. use std::sync::Mutex;
  33. // 注意:AtomicU64 和 Ordering 导入暂时保留,为未来优化预留
  34. // #[allow(dead_code)] use std::sync::atomic::{AtomicU64, Ordering};
  35. /// 全局 CPU 时间缓存,用于增量计算
  36. static CPU_PREV_OVERALL: Mutex<Option<CpuTimes>> = Mutex::new(None);
  37. static CPU_PREV_PER_CORE: Mutex<Vec<CpuTimes>> = Mutex::new(Vec::new());
  38. static CPU_TIMES_INIT: std::sync::Once = std::sync::Once::new();
  39. /// 系统资源统计数据结构
  40. #[derive(Debug, Clone)]
  41. pub struct SystemStats {
  42. pub hostname: String,
  43. pub cpu_usage: f32, // CPU 使用率 (0.0-1.0) - 保持向后兼容
  44. pub cpu_stats: CpuStats, // 详细的 CPU 统计信息
  45. pub memory_total: u64, // 总内存字节数
  46. pub memory_used: u64, // 已用内存字节数
  47. pub memory_available: u64, // 可用内存字节数
  48. pub memory_cached: u64, // 缓存内存字节数
  49. pub memory_free: u64, // 空闲内存字节数
  50. pub timestamp: Instant, // 数据获取时间戳
  51. }
  52. impl Default for SystemStats {
  53. #[inline]
  54. fn default() -> Self {
  55. Self {
  56. hostname: "未知主机".to_string(),
  57. cpu_usage: 0.0,
  58. cpu_stats: CpuStats {
  59. overall: CpuUsageBreakdown::default(),
  60. per_core: Vec::new(),
  61. core_count: 0,
  62. },
  63. memory_total: 0,
  64. memory_used: 0,
  65. memory_available: 0,
  66. memory_cached: 0,
  67. memory_free: 0,
  68. timestamp: Instant::now(),
  69. }
  70. }
  71. }
  72. /// 系统资源获取错误类型
  73. #[derive(Debug)]
  74. pub enum StatsError {
  75. IoError(std::io::Error),
  76. ParseError(String),
  77. #[allow(dead_code)] // 为未来跨平台支持预留
  78. UnsupportedPlatform,
  79. }
  80. impl From<std::io::Error> for StatsError {
  81. #[inline]
  82. fn from(error: std::io::Error) -> Self {
  83. StatsError::IoError(error)
  84. }
  85. }
  86. impl std::fmt::Display for StatsError {
  87. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  88. match self {
  89. StatsError::IoError(e) => write!(f, "IO 错误: {e}"),
  90. StatsError::ParseError(s) => write!(f, "解析错误: {s}"),
  91. StatsError::UnsupportedPlatform => write!(f, "不支持的平台"),
  92. }
  93. }
  94. }
  95. impl std::error::Error for StatsError {}
  96. pub type Result<T> = std::result::Result<T, StatsError>;
  97. /// 收集系统统计数据
  98. pub async fn collect_system_stats() -> Result<SystemStats> {
  99. #[cfg(target_os = "linux")]
  100. {
  101. collect_linux_stats().await
  102. }
  103. #[cfg(not(target_os = "linux"))]
  104. {
  105. Err(StatsError::UnsupportedPlatform)
  106. }
  107. }
  108. /// Linux 系统统计数据收集
  109. #[cfg(target_os = "linux")]
  110. async fn collect_linux_stats() -> Result<SystemStats> {
  111. let hostname = get_hostname()?;
  112. let cpu_stats = get_cpu_stats().await?;
  113. let cpu_usage = cpu_stats.overall.total_percent / 100.0; // 转换为 0.0-1.0 范围
  114. let memory_info = get_memory_info().await?;
  115. Ok(SystemStats {
  116. hostname,
  117. cpu_usage,
  118. cpu_stats,
  119. memory_total: memory_info.total,
  120. memory_used: memory_info.used,
  121. memory_available: memory_info.available,
  122. memory_cached: memory_info.cached,
  123. memory_free: memory_info.free,
  124. timestamp: Instant::now(),
  125. })
  126. }
  127. /// 获取主机名
  128. #[cfg(target_os = "linux")]
  129. #[inline]
  130. fn get_hostname() -> Result<String> {
  131. std::fs::read_to_string("/proc/sys/kernel/hostname")
  132. .map(|s| s.trim().to_string())
  133. .map_err(From::from)
  134. }
  135. /// 内存信息结构
  136. #[derive(Debug, Default)]
  137. struct MemoryInfo {
  138. total: u64,
  139. used: u64,
  140. available: u64,
  141. cached: u64,
  142. free: u64,
  143. }
  144. /// 获取内存信息
  145. #[cfg(target_os = "linux")]
  146. async fn get_memory_info() -> Result<MemoryInfo> {
  147. // 预估 /proc/meminfo 的大小,预分配容量
  148. let mut content = String::with_capacity(2048);
  149. let file_content = tokio::fs::read_to_string("/proc/meminfo").await?;
  150. content.push_str(&file_content);
  151. let mut info = MemoryInfo::default();
  152. for line in content.lines() {
  153. let mut parts = line.split_whitespace();
  154. if let (Some(key), Some(value)) = (parts.next(), parts.next()) {
  155. let value = value.parse::<u64>().unwrap_or(0) * 1024; // 转换为字节
  156. match key {
  157. "MemTotal:" => info.total = value,
  158. "MemAvailable:" => info.available = value,
  159. "Cached:" => info.cached = value,
  160. "MemFree:" => info.free = value,
  161. _ => {}
  162. }
  163. }
  164. }
  165. // 计算已用内存 = 总内存 - 可用内存
  166. info.used = info.total.saturating_sub(info.available);
  167. Ok(info)
  168. }
  169. /// 解析 CPU 时间统计(为未来功能预留)
  170. #[cfg(target_os = "linux")]
  171. #[inline]
  172. #[allow(dead_code)] // 为未来功能预留
  173. fn parse_cpu_times(content: &str) -> Result<CpuTimes> {
  174. // 解析第一行 CPU 总时间
  175. let first_line = content
  176. .lines()
  177. .next()
  178. .ok_or_else(|| StatsError::ParseError("无法解析 /proc/stat".to_string()))?;
  179. let mut parts = first_line.split_whitespace().skip(1); // 跳过 "cpu"
  180. let user: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
  181. let nice: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
  182. let system: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
  183. let idle: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
  184. let iowait: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
  185. let irq: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
  186. let softirq: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
  187. // 忽略其他字段 (steal, guest, guest_nice)
  188. let total = user + nice + system + idle + iowait + irq + softirq;
  189. Ok(CpuTimes {
  190. user,
  191. nice,
  192. system,
  193. idle,
  194. iowait,
  195. irq,
  196. softirq,
  197. total,
  198. })
  199. }
  200. /// 解析所有 CPU 核心的时间统计
  201. #[cfg(target_os = "linux")]
  202. #[inline]
  203. fn parse_all_cpu_times(content: &str) -> Result<(CpuTimes, Vec<CpuTimes>)> {
  204. let lines = content.lines();
  205. let mut overall_times = None;
  206. let mut per_core_times = Vec::new();
  207. for line in lines {
  208. if line.starts_with("cpu") {
  209. let mut parts = line.split_whitespace();
  210. let cpu_label = parts.next().unwrap_or("");
  211. let user: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
  212. let nice: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
  213. let system: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
  214. let idle: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
  215. let iowait: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
  216. let irq: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
  217. let softirq: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
  218. let total = user + nice + system + idle + iowait + irq + softirq;
  219. let times = CpuTimes {
  220. user,
  221. nice,
  222. system,
  223. idle,
  224. iowait,
  225. irq,
  226. softirq,
  227. total,
  228. };
  229. if cpu_label == "cpu" {
  230. overall_times = Some(times);
  231. } else if cpu_label.starts_with("cpu") {
  232. per_core_times.push(times);
  233. }
  234. }
  235. }
  236. match overall_times {
  237. Some(overall) => Ok((overall, per_core_times)),
  238. None => Err(StatsError::ParseError("无法找到 CPU 统计信息".to_string())),
  239. }
  240. }
  241. /// CPU 使用率计算(使用增量算法)(为向后兼容预留)
  242. #[cfg(target_os = "linux")]
  243. #[allow(dead_code)] // 为向后兼容预留
  244. async fn get_cpu_usage() -> Result<f32> {
  245. let cpu_stats = get_cpu_stats().await?;
  246. Ok(cpu_stats.overall.total_percent / 100.0)
  247. }
  248. /// 获取详细的 CPU 统计信息
  249. #[cfg(target_os = "linux")]
  250. async fn get_cpu_stats() -> Result<CpuStats> {
  251. // 预估 /proc/stat 的大小,预分配容量
  252. let mut content = String::with_capacity(2048);
  253. let file_content = tokio::fs::read_to_string("/proc/stat").await?;
  254. content.push_str(&file_content);
  255. let (current_overall, current_per_core) = parse_all_cpu_times(&content)?;
  256. // 获取之前的时间统计(线程安全)
  257. let (prev_overall, prev_per_core) = {
  258. let mut prev_overall_guard = CPU_PREV_OVERALL.lock().unwrap();
  259. let mut prev_per_core_guard = CPU_PREV_PER_CORE.lock().unwrap();
  260. CPU_TIMES_INIT.call_once(|| {
  261. *prev_overall_guard = Some(current_overall.clone());
  262. prev_per_core_guard.clone_from(&current_per_core);
  263. });
  264. (prev_overall_guard.clone(), prev_per_core_guard.clone())
  265. };
  266. // 如果是第一次调用,返回 0 使用率
  267. let overall_usage = if let (Some(prev_overall), _) = (&prev_overall, &prev_per_core) {
  268. calculate_cpu_usage_breakdown(prev_overall, &current_overall)
  269. } else {
  270. CpuUsageBreakdown::default()
  271. };
  272. // 计算每个 CPU 核心的使用率
  273. let mut per_core_usage = Vec::new();
  274. for (i, current_core) in current_per_core.iter().enumerate() {
  275. if let Some(prev_core) = prev_per_core.get(i) {
  276. per_core_usage.push(calculate_cpu_usage_breakdown(prev_core, current_core));
  277. } else {
  278. per_core_usage.push(CpuUsageBreakdown::default());
  279. }
  280. }
  281. // 更新全局缓存
  282. {
  283. let mut prev_overall_guard = CPU_PREV_OVERALL.lock().unwrap();
  284. let mut prev_per_core_guard = CPU_PREV_PER_CORE.lock().unwrap();
  285. *prev_overall_guard = Some(current_overall.clone());
  286. *prev_per_core_guard = current_per_core.clone();
  287. }
  288. Ok(CpuStats {
  289. overall: overall_usage,
  290. per_core: per_core_usage,
  291. core_count: current_per_core.len(),
  292. })
  293. }
  294. /// 计算两个时间点之间的 CPU 使用率分解
  295. #[inline]
  296. fn calculate_cpu_usage_breakdown(prev: &CpuTimes, current: &CpuTimes) -> CpuUsageBreakdown {
  297. // 计算增量
  298. let total_diff = current.total.saturating_sub(prev.total);
  299. if total_diff == 0 {
  300. return CpuUsageBreakdown::default();
  301. }
  302. let user_diff = current.user.saturating_sub(prev.user);
  303. let nice_diff = current.nice.saturating_sub(prev.nice);
  304. let system_diff = current.system.saturating_sub(prev.system);
  305. let idle_diff = current.idle.saturating_sub(prev.idle);
  306. // 计算各分量的使用率百分比
  307. let user_percent = (user_diff as f32 / total_diff as f32) * 100.0;
  308. let nice_percent = (nice_diff as f32 / total_diff as f32) * 100.0;
  309. let system_percent = (system_diff as f32 / total_diff as f32) * 100.0;
  310. let total_percent = (total_diff.saturating_sub(idle_diff) as f32 / total_diff as f32) * 100.0;
  311. CpuUsageBreakdown {
  312. user_percent: user_percent.clamp(0.0, 100.0),
  313. nice_percent: nice_percent.clamp(0.0, 100.0),
  314. system_percent: system_percent.clamp(0.0, 100.0),
  315. total_percent: total_percent.clamp(0.0, 100.0),
  316. }
  317. }
  318. #[cfg(test)]
  319. mod tests {
  320. use super::*;
  321. #[test]
  322. fn test_system_stats_default() {
  323. let stats = SystemStats::default();
  324. assert_eq!(stats.hostname, "未知主机");
  325. assert_eq!(stats.cpu_usage, 0.0);
  326. assert_eq!(stats.memory_total, 0);
  327. assert_eq!(stats.memory_used, 0);
  328. assert_eq!(stats.memory_available, 0);
  329. assert_eq!(stats.memory_cached, 0);
  330. assert_eq!(stats.memory_free, 0);
  331. }
  332. #[test]
  333. fn test_cpu_times_default() {
  334. let times = CpuTimes::default();
  335. assert_eq!(times.user, 0);
  336. assert_eq!(times.nice, 0);
  337. assert_eq!(times.system, 0);
  338. assert_eq!(times.idle, 0);
  339. assert_eq!(times.total, 0);
  340. }
  341. #[test]
  342. fn test_parse_cpu_times_valid() {
  343. let content = "cpu 1234 567 890 1234 0 0 0 0 0 0";
  344. let times = parse_cpu_times(content).unwrap();
  345. assert_eq!(times.user, 1234);
  346. assert_eq!(times.nice, 567);
  347. assert_eq!(times.system, 890);
  348. assert_eq!(times.idle, 1234);
  349. assert_eq!(times.total, 1234 + 567 + 890 + 1234);
  350. }
  351. #[test]
  352. fn test_parse_cpu_times_invalid() {
  353. let content = "invalid content";
  354. let result = parse_cpu_times(content).unwrap();
  355. assert_eq!(result.total, 0);
  356. assert_eq!(result.idle, 0);
  357. }
  358. #[test]
  359. fn test_parse_cpu_times_empty() {
  360. let content = "";
  361. assert!(parse_cpu_times(content).is_err());
  362. }
  363. #[test]
  364. fn test_stats_error_display() {
  365. let io_error = StatsError::IoError(std::io::Error::new(
  366. std::io::ErrorKind::NotFound,
  367. "test error",
  368. ));
  369. assert_eq!(format!("{}", io_error), "IO 错误: test error");
  370. let parse_error = StatsError::ParseError("test parse error".to_string());
  371. assert_eq!(format!("{}", parse_error), "解析错误: test parse error");
  372. let unsupported_error = StatsError::UnsupportedPlatform;
  373. assert_eq!(format!("{}", unsupported_error), "不支持的平台");
  374. }
  375. #[test]
  376. fn test_stats_error_from_io() {
  377. let io_error =
  378. std::io::Error::new(std::io::ErrorKind::PermissionDenied, "permission denied");
  379. let stats_error = StatsError::from(io_error);
  380. match stats_error {
  381. StatsError::IoError(_) => {} // 预期的类型
  382. _ => panic!("应该是 IoError 类型"),
  383. }
  384. }
  385. #[tokio::test]
  386. #[cfg(target_os = "linux")]
  387. async fn test_get_hostname() {
  388. // 测试获取主机名
  389. match get_hostname() {
  390. Ok(hostname) => {
  391. assert!(!hostname.is_empty());
  392. println!("主机名: {}", hostname);
  393. }
  394. Err(e) => {
  395. // 在某些环境中可能失败,这是可以接受的
  396. println!("获取主机名失败: {}", e);
  397. }
  398. }
  399. }
  400. #[tokio::test]
  401. #[cfg(target_os = "linux")]
  402. async fn test_get_memory_info() {
  403. // 测试获取内存信息
  404. match get_memory_info().await {
  405. Ok(info) => {
  406. assert!(info.total > 0);
  407. assert!(info.used <= info.total);
  408. assert!(info.available <= info.total);
  409. assert!(info.cached <= info.total);
  410. assert!(info.free <= info.total);
  411. println!("内存信息: {:?}", info);
  412. }
  413. Err(e) => {
  414. // 在某些环境中可能失败
  415. println!("获取内存信息失败: {}", e);
  416. }
  417. }
  418. }
  419. #[tokio::test]
  420. #[cfg(target_os = "linux")]
  421. async fn test_collect_linux_stats() {
  422. // 测试完整的 Linux 统计数据收集
  423. match collect_linux_stats().await {
  424. Ok(stats) => {
  425. assert!(!stats.hostname.is_empty());
  426. assert!(stats.cpu_usage >= 0.0 && stats.cpu_usage <= 1.0);
  427. assert!(stats.memory_total > 0);
  428. println!("系统统计: {:?}", stats);
  429. }
  430. Err(e) => {
  431. // 在某些环境中可能失败
  432. println!("收集系统统计失败: {}", e);
  433. }
  434. }
  435. }
  436. #[tokio::test]
  437. #[cfg(not(target_os = "linux"))]
  438. async fn test_collect_system_stats_unsupported() {
  439. // 测试非 Linux 平台
  440. let result = collect_system_stats().await;
  441. assert!(result.is_err());
  442. match result.unwrap_err() {
  443. StatsError::UnsupportedPlatform => {} // 预期的错误
  444. _ => panic!("应该是 UnsupportedPlatform 错误"),
  445. }
  446. }
  447. #[test]
  448. fn test_cpu_usage_breakdown_default() {
  449. let breakdown = CpuUsageBreakdown::default();
  450. assert_eq!(breakdown.user_percent, 0.0);
  451. assert_eq!(breakdown.nice_percent, 0.0);
  452. assert_eq!(breakdown.system_percent, 0.0);
  453. assert_eq!(breakdown.total_percent, 0.0);
  454. }
  455. #[test]
  456. fn test_parse_all_cpu_times_valid() {
  457. let content = "cpu 1234 567 890 1234 100 200 300 0 0 0\n\
  458. cpu0 617 283 445 617 50 100 150\n\
  459. cpu1 617 284 445 617 50 100 150";
  460. let (overall, per_core) = parse_all_cpu_times(content).unwrap();
  461. assert_eq!(overall.user, 1234);
  462. assert_eq!(overall.nice, 567);
  463. assert_eq!(overall.system, 890);
  464. assert_eq!(overall.idle, 1234);
  465. assert_eq!(overall.iowait, 100);
  466. assert_eq!(overall.irq, 200);
  467. assert_eq!(overall.softirq, 300);
  468. assert_eq!(per_core.len(), 2);
  469. assert_eq!(per_core[0].user, 617);
  470. assert_eq!(per_core[1].user, 617);
  471. }
  472. #[test]
  473. fn test_calculate_cpu_usage_breakdown() {
  474. let prev = CpuTimes {
  475. user: 100,
  476. nice: 20,
  477. system: 50,
  478. idle: 800,
  479. iowait: 10,
  480. irq: 5,
  481. softirq: 15,
  482. total: 1000,
  483. };
  484. let current = CpuTimes {
  485. user: 200,
  486. nice: 30,
  487. system: 80,
  488. idle: 1500,
  489. iowait: 20,
  490. irq: 10,
  491. softirq: 20,
  492. total: 1860,
  493. };
  494. let breakdown = calculate_cpu_usage_breakdown(&prev, &current);
  495. // 计算增量:total_diff = 860, user_diff = 100, nice_diff = 10, system_diff = 30, idle_diff = 700
  496. assert!((breakdown.user_percent - 11.63).abs() < 0.1); // 100/860 * 100
  497. assert!((breakdown.nice_percent - 1.16).abs() < 0.1); // 10/860 * 100
  498. assert!((breakdown.system_percent - 3.49).abs() < 0.1); // 30/860 * 100
  499. assert!((breakdown.total_percent - 18.60).abs() < 0.1); // 160/860 * 100
  500. }
  501. #[test]
  502. fn test_calculate_cpu_usage_breakdown_zero_diff() {
  503. let prev = CpuTimes {
  504. user: 100,
  505. nice: 20,
  506. system: 50,
  507. idle: 800,
  508. iowait: 10,
  509. irq: 5,
  510. softirq: 15,
  511. total: 1000,
  512. };
  513. let current = prev.clone();
  514. let breakdown = calculate_cpu_usage_breakdown(&prev, &current);
  515. assert_eq!(breakdown.user_percent, 0.0);
  516. assert_eq!(breakdown.nice_percent, 0.0);
  517. assert_eq!(breakdown.system_percent, 0.0);
  518. assert_eq!(breakdown.total_percent, 0.0);
  519. }
  520. #[tokio::test]
  521. #[cfg(target_os = "linux")]
  522. async fn test_get_cpu_stats() {
  523. // 测试获取 CPU 统计信息
  524. match get_cpu_stats().await {
  525. Ok(stats) => {
  526. assert!(stats.core_count > 0);
  527. assert!(stats.per_core.len() == stats.core_count);
  528. assert!(stats.overall.total_percent >= 0.0 && stats.overall.total_percent <= 100.0);
  529. // 检查各个分量的合理性
  530. assert!(stats.overall.user_percent >= 0.0 && stats.overall.user_percent <= 100.0);
  531. assert!(stats.overall.nice_percent >= 0.0 && stats.overall.nice_percent <= 100.0);
  532. assert!(
  533. stats.overall.system_percent >= 0.0 && stats.overall.system_percent <= 100.0
  534. );
  535. println!("CPU 统计: {:?}", stats);
  536. }
  537. Err(e) => {
  538. // 在某些环境中可能失败
  539. println!("获取 CPU 统计失败: {}", e);
  540. }
  541. }
  542. }
  543. #[test]
  544. fn test_cpu_times_new_fields() {
  545. // 更新现有的测试以包含新字段
  546. let times = CpuTimes::default();
  547. assert_eq!(times.user, 0);
  548. assert_eq!(times.nice, 0);
  549. assert_eq!(times.system, 0);
  550. assert_eq!(times.idle, 0);
  551. assert_eq!(times.iowait, 0); // 新字段
  552. assert_eq!(times.irq, 0); // 新字段
  553. assert_eq!(times.softirq, 0); // 新字段
  554. assert_eq!(times.total, 0);
  555. }
  556. }