Measure real CPU load

This commit is contained in:
FliegendeWurst 2020-05-17 11:17:38 +02:00
parent 2322feb5b7
commit b239e015c8
No known key found for this signature in database
GPG Key ID: CA38E82B54B32A88
2 changed files with 28 additions and 11 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
target

View File

@ -1,15 +1,31 @@
use std::fs; use std::fs;
const WAIT_MS: u32 = 500;
fn main() { fn main() {
let load = fs::read_to_string("/proc/loadavg").unwrap().split(' ').nth(0).unwrap().parse::<f64>().unwrap(); let stat_1 = extract_stat();
let num_cpus = fs::read_dir("/sys/devices/system/cpu").unwrap() std::thread::sleep_ms(WAIT_MS);
.map(|x| x.unwrap().file_name().into_string().unwrap()) let stat_2 = extract_stat();
.filter(|x| x.starts_with("cpu") && x.chars().nth(3).unwrap().is_numeric()) /*
.count() as f64; let load = fs::read_to_string("/proc/loadavg").unwrap().split(' ').nth(0).unwrap().parse::<f64>().unwrap();
let temp = fs::read_to_string("/sys/class/hwmon/hwmon0/temp1_input").unwrap().trim().parse::<f64>().unwrap() / 1000.0; let num_cpus = fs::read_dir("/sys/devices/system/cpu").unwrap()
let meminfo = fs::read_to_string("/proc/meminfo").unwrap(); .map(|x| x.unwrap().file_name().into_string().unwrap())
let mut meminfo = meminfo.split('\n'); .filter(|x| x.starts_with("cpu") && x.chars().nth(3).unwrap().is_numeric())
let total = meminfo.next().unwrap().split_whitespace().nth(1).unwrap().parse::<u64>().unwrap() / 1_000; .count() as f64;
let available = meminfo.nth(1).unwrap().split_whitespace().nth(1).unwrap().parse::<u64>().unwrap() / 1_000; */
println!("{:.1}% {:.1}°C {}/{}MB", load / num_cpus * 100.0, temp, total - available, total); 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::<f64>().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::<u64>().unwrap() / 1_000;
let available = meminfo.nth(1).unwrap().split_whitespace().nth(1).unwrap().parse::<u64>().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::<u64>().unwrap()).sum::<u64>()
} }