Skip to content

Commit

Permalink
Ugly workaround for float overflow when computing CPU% of PID
Browse files Browse the repository at this point in the history
This should be done in a better way but I can't be bothered, just cap
CPU% value to max cores.

Closes #24

Resolves: <#24>
Signed-off-by: Manos Pitsidianakis <[email protected]>
  • Loading branch information
epilys committed Nov 15, 2024
1 parent 9c9bd05 commit a69d398
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 9 deletions.
6 changes: 4 additions & 2 deletions src/components/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -444,7 +444,7 @@ impl Component for KernelMetrics {
);

for (i, (tag, s, fg_color, bg_color, attr)) in
get_cpu_times(&old_cpu_stat, &self.cpu_stat[0])
get_cpu_times(&old_cpu_stat, &self.cpu_stat[0], self.cpu_stat.len())
.into_iter()
.enumerate()
{
Expand Down Expand Up @@ -565,15 +565,17 @@ fn get_loadavg() -> [String; 3] {
fn get_cpu_times(
old_cpu_stat: &Stat,
cpu_stat: &Stat,
num_cores: usize,
) -> Vec<(&'static str, String, Color, Color, Attr)> {
let mut ret = Vec::new();

macro_rules! val {
($tag:literal, $field:tt) => {
let percent = (cpu_stat.$field.saturating_sub(old_cpu_stat.$field)) as f64
let mut percent = (cpu_stat.$field.saturating_sub(old_cpu_stat.$field)) as f64
/ (cpu_stat
.total_time()
.saturating_sub(old_cpu_stat.total_time())) as f64;
percent = percent.min(num_cores as f64);
let s = format!("{:.1}%", percent * 100.0);
ret.push((
$tag,
Expand Down
16 changes: 9 additions & 7 deletions src/components/processes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1906,13 +1906,15 @@ fn get(data: &mut ProcessData, follow_pid: Option<Pid>, sort: Sort) -> Vec<Proce
ppid: PpidString(process.ppid.to_string()),
vm_rss: VmRssString(Bytes(process.vm_rss * 1024).as_convenient_string()),
vm_rss_value: process.vm_rss * 1024,
cpu_percent: ((multiplier
* (process.rtime
- processes_times
.get(&process.pid)
.copied()
.unwrap_or(process.rtime)) as f64)
/ divisor) as usize,
cpu_percent: (cpu_no * 10000).min(
((multiplier
* (process.rtime
- processes_times
.get(&process.pid)
.copied()
.unwrap_or(process.rtime)) as f64)
/ divisor) as usize,
),
rtime: process.rtime,
state: process.state,
cmd_line: CmdLineString(process.cmd_line),
Expand Down

0 comments on commit a69d398

Please sign in to comment.