fix cpu time again

This commit is contained in:
Robin Appelman 2021-03-28 23:28:07 +02:00
commit 76b34af04f
2 changed files with 15 additions and 5 deletions

View file

@ -17,7 +17,7 @@ pub fn get_metrics() -> Result<String> {
let pools = pools(); let pools = pools();
let networks = network_stats()?; let networks = network_stats()?;
let mut result = String::with_capacity(256); let mut result = String::with_capacity(256);
writeln!(&mut result, "cpu_time{{host=\"{}\"}} {:.1}", hostname, cpu).ok(); writeln!(&mut result, "cpu_time{{host=\"{}\"}} {:.3}", hostname, cpu).ok();
writeln!( writeln!(
&mut result, &mut result,
"memory_total{{host=\"{}\"}} {}", "memory_total{{host=\"{}\"}} {}",

View file

@ -111,7 +111,7 @@ pub fn memory() -> Result<Memory> {
Ok(mem) Ok(mem)
} }
pub fn cpu_time() -> Result<u64> { pub fn cpu_time() -> Result<f32> {
let stat = BufReader::new(File::open("/proc/stat")?); let stat = BufReader::new(File::open("/proc/stat")?);
let line = stat let line = stat
.lines() .lines()
@ -121,9 +121,9 @@ pub fn cpu_time() -> Result<u64> {
if let (_cpu, Some(user), _nice, Some(system)) = if let (_cpu, Some(user), _nice, Some(system)) =
(parts.next(), parts.next(), parts.next(), parts.next()) (parts.next(), parts.next(), parts.next(), parts.next())
{ {
let user: u64 = user.parse()?; let user: f32 = user.parse()?;
let system: u64 = system.parse()?; let system: f32 = system.parse()?;
Ok((user + system) / clock_ticks()?) Ok((user + system) / (clock_ticks()? as f32) / (cpu_count()? as f32))
} else { } else {
Err(Report::msg("Invalid /proc/stat")) Err(Report::msg("Invalid /proc/stat"))
} }
@ -241,3 +241,13 @@ fn statvfs(path: &CStr) -> Result<libc::statvfs> {
Err(Report::msg("Failed to stat vfs")) Err(Report::msg("Failed to stat vfs"))
} }
} }
fn cpu_count() -> Result<u64> {
let result = unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) };
if result < 0 {
Err(Report::msg("Failed to get cpu count"))
} else {
Ok(result as u64)
}
}