Skip to content

Commit

Permalink
Return negative total CPU % if it cannot be calculated (*very* old ke…
Browse files Browse the repository at this point in the history
…rnel, older than 2.6.33 released 2010)

Signed-off-by: DL6ER <[email protected]>
  • Loading branch information
DL6ER committed Feb 27, 2025
1 parent 41abff8 commit 1102aa1
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/api/docs/content/specs/info.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -463,7 +463,7 @@ components:
example: 8
"%cpu":
type: number
description: Total CPU usage in percent
description: Total CPU usage in percent (may be higher than 100% on multi-core systems and negative if the value cannot be computed)
example: 0.0
load:
type: object
Expand Down
10 changes: 8 additions & 2 deletions src/daemon.c
Original file line number Diff line number Diff line change
Expand Up @@ -462,22 +462,28 @@ void calc_cpu_usage(const unsigned int interval)
static float last_ftl_cpu_time = 0.0f;
ftl_cpu_usage = 100.0 * (ftl_cpu_time - last_ftl_cpu_time) / interval;

// Store the current time for the next call to this function
last_ftl_cpu_time = ftl_cpu_time;

// The number of clock ticks per second
static long user_hz = 0;
if(user_hz == 0)
user_hz = sysconf(_SC_CLK_TCK);

// Calculate the total CPU usage
unsigned long total_total, total_idle;
parse_proc_stat(&total_total, &total_idle);
if(!parse_proc_stat(&total_total, &total_idle))
{
total_cpu_usage = -1.0f;
return;
}

// Calculate the CPU usage since the last call to this function
static unsigned long last_total_total = 0, last_total_idle = 0;
if(total_total - last_total_total > 0)
total_cpu_usage = 100.0 * (total_total - last_total_total - (total_idle - last_total_idle)) / (total_total - last_total_total);

// Store the current time for the next call to this function
last_ftl_cpu_time = ftl_cpu_time;
last_total_idle = total_idle;
last_total_total = total_total;
}
Expand Down

0 comments on commit 1102aa1

Please sign in to comment.