From b239e015c8138b987fae5263f1d2dac99d58b273 Mon Sep 17 00:00:00 2001 From: FliegendeWurst <2012gdwu@web.de> Date: Sun, 17 May 2020 11:17:38 +0200 Subject: [PATCH] Measure real CPU load --- .gitignore | 1 + src/main.rs | 38 +++++++++++++++++++++++++++----------- 2 files changed, 28 insertions(+), 11 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..eb5a316 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +target diff --git a/src/main.rs b/src/main.rs index adade9e..da2dc17 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,15 +1,31 @@ use std::fs; +const WAIT_MS: u32 = 500; + fn main() { - let load = fs::read_to_string("/proc/loadavg").unwrap().split(' ').nth(0).unwrap().parse::().unwrap(); - let num_cpus = fs::read_dir("/sys/devices/system/cpu").unwrap() - .map(|x| x.unwrap().file_name().into_string().unwrap()) - .filter(|x| x.starts_with("cpu") && x.chars().nth(3).unwrap().is_numeric()) - .count() as f64; - let temp = fs::read_to_string("/sys/class/hwmon/hwmon0/temp1_input").unwrap().trim().parse::().unwrap() / 1000.0; - let meminfo = fs::read_to_string("/proc/meminfo").unwrap(); - let mut meminfo = meminfo.split('\n'); - let total = meminfo.next().unwrap().split_whitespace().nth(1).unwrap().parse::().unwrap() / 1_000; - let available = meminfo.nth(1).unwrap().split_whitespace().nth(1).unwrap().parse::().unwrap() / 1_000; - println!("{:.1}% {:.1}°C {}/{}MB", load / num_cpus * 100.0, temp, total - available, total); + let stat_1 = extract_stat(); + std::thread::sleep_ms(WAIT_MS); + let stat_2 = extract_stat(); + /* + let load = fs::read_to_string("/proc/loadavg").unwrap().split(' ').nth(0).unwrap().parse::().unwrap(); + let num_cpus = fs::read_dir("/sys/devices/system/cpu").unwrap() + .map(|x| x.unwrap().file_name().into_string().unwrap()) + .filter(|x| x.starts_with("cpu") && x.chars().nth(3).unwrap().is_numeric()) + .count() as f64; + */ + let real_load = (stat_2 - stat_1) * 1000 / (WAIT_MS as u64); + let temp = fs::read_to_string("/sys/class/hwmon/hwmon0/temp1_input").unwrap().trim().parse::().unwrap() / 1000.0; + let meminfo = fs::read_to_string("/proc/meminfo").unwrap(); + let mut meminfo = meminfo.split('\n'); + let total = meminfo.next().unwrap().split_whitespace().nth(1).unwrap().parse::().unwrap() / 1_000; + let available = meminfo.nth(1).unwrap().split_whitespace().nth(1).unwrap().parse::().unwrap() / 1_000; + //println!("{:.1}% {:.1}°C {}/{}MB", load / num_cpus * 100.0, temp, total - available, total); + println!("{}% {:.1}°C {}/{}MB", real_load, temp, total - available, total); +} + +fn extract_stat() -> u64 { + let stat = fs::read_to_string("/proc/stat").unwrap(); + let cpu = stat.lines().find(|x| x.starts_with("cpu ")).unwrap(); + let times = cpu.split(' '); + times.skip(1).filter(|x| !x.is_empty()).take(3).map(|x| x.parse::().unwrap()).sum::() }