Determining CPU utilization

≡放荡痞女 提交于 2019-11-29 07:10:07

问题


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.


回答1:


You need to sample the values in /proc/stat at two times, and calculate the average utilisation over that time. (Instantaneous utilisation doesn't make a whole lot of sense - it'll always be 100% on a single core machine, since your utilsation-measuring code is running whenever it looks).




回答2:


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.




回答3:


cat /proc/stat

you will see something like this

cpu  178877 11039 58012 5027374 22025 2616 1298 0 0
cpu0 122532 8808 34213 2438147 10881 1050 448 0 0
cpu1 56344 2230 23799 2589227 11143 1565 850 0 0

Simply take the sums of first three numbers and divide them with sums of first four integer

The first 4 numbers are user, nice, system, and idle times

note: This gives overall average. If you want to take spontaneous average, you should take two samples and subtract them from each other before the divide.




回答4:


The /proc filesystem has all kinds of interesting information. Look at man proc for more information.




回答5:


Just use top if it is available. You can use it in a non-interactive mode:

top -n 1

If you want something specific then just grep that output. The exact details will depend on how your top command formats its output, but for example:

top -n 1 | grep 'Load'


来源:https://stackoverflow.com/questions/3769405/determining-cpu-utilization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!