Is there a command or any other way to get the current or average CPU utilization (for a multi-processor environment) in Linux?
I am using embedded Linux in a small system. Basically, I need to determine the CPU utilization, so that if it is high, I can instead divert a new process to another controller in the system, rather than executing on the main processor, which could be busy doing a more important process.
This question is not about merely prioritizing processes, the other controller can sufficiently handle the new process, just that when the main processor is not busy, I would prefer it to do the execution.
The answer to the question after much searching and tinkering:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
long double a[4], b[4], loadavg;
FILE *fp;
char dump[50];
for(;;)
{
fp = fopen("/proc/stat","r");
fscanf(fp,"%*s %Lf %Lf %Lf %Lf",&a[0],&a[1],&a[2],&a[3]);
fclose(fp);
sleep(1);
fp = fopen("/proc/stat","r");
fscanf(fp,"%*s %Lf %Lf %Lf %Lf",&b[0],&b[1],&b[2],&b[3]);
fclose(fp);
loadavg = ((b[0]+b[1]+b[2]) - (a[0]+a[1]+a[2])) / ((b[0]+b[1]+b[2]+b[3]) - (a[0]+a[1]+a[2]+a[3]));
printf("The current CPU utilization is : %Lf\n",loadavg);
}
return(0);
}
I am getting the same values as those reported by the System Monitor.