0

From This and this link i am trying to calculate CPU utilization but it is not coming as expected. (i.e. My application is showing CPU utilization as 3% and top is showing 99%.)

I am trying below method,

usage=100*(((utime_ticks_current + cutime_ticks_current + stime_ticks_current + cstime_ticks_current) - (utime_ticks_prev + cutime_ticks_prev + stime_ticks_prev + cstime_ticks_prev)) / (long)(total_cpu_time_current - total_cpu_time_prev))

here, 
utime_ticks = /proc/pid/stat -> 14th value
stime_ticks = /proc/pid/stat -> 15th value
cutime_ticks = /proc/pid/stat -> 16th value
cstime_ticks = /proc/pid/stat -> 17th value

total_cpu_time = /proc/stat -> sum of all 10 values

Time difference between current and prev is 1 second.

Also, I have manually checked that all the values for all the variables are correct only.

Please note that i tried the same thing separately for "stime , cstime" and "utime , cutime"

I think there is some problem in the way i am calculating it,

Can anyone please help?


I only found the solution, I just had to multiply the value with total number of Cores/CPU available.


Community
  • 1
  • 1
Chirag
  • 607
  • 1
  • 6
  • 17

1 Answers1

0

I can give you part of the code I use for my cpu utilization server. It is very accurate.

long double a[4], b[4], loadavg;
FILE *fp;
char dump[50] = {0};
memset(dump, 0, 50);

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]));
loadavg=loadavg*100;
sprintf(dump, "%Lf\n",loadavg);
long double used;
Mirakurun
  • 4,859
  • 5
  • 16
  • 32
  • Thank you, but i want to calculate CPU utilization for each process,i think above code will give CPU utilization for each core. – Chirag Aug 17 '16 at 14:25