I’m writing a small program in C that will output a total percentage of CPU usage over a 1 second period. I’ve got it working for the most part, it does calculate the proper numbers but the final calculation where it divides workOver by totalOver * 100 it always outputs 0. I’m not sure why. Any help would be great. Code is below.
#include <stdio.h>
#include <glibtop.h>
#include <glibtop/cpu.h>
#include <unistd.h>
#include <math.h>
unsigned long cpu1Total, cpu1User, cpu1Nice, cpu1Sys, cpu1Work;
unsigned long cpu2Total, cpu2User, cpu2Nice, cpu2Sys, cpu2Work;
unsigned long workOver, totalOver, cpuTotal;
int main(){
glibtop_init();
glibtop_cpu cpu;
glibtop_get_cpu (&cpu);
cpu1Total = cpu.total;
cpu1User = cpu.user;
cpu1Nice = cpu.nice;
cpu1Sys = cpu.sys;
cpu1Work = cpu1User + cpu1Nice + cpu1Sys;
usleep ( 1000000 ) ;
glibtop_get_cpu (&cpu);
cpu2Total = cpu.total;
cpu2User = cpu.user;
cpu2Nice = cpu.nice;
cpu2Sys = cpu.sys;
cpu2Work = cpu2User + cpu2Nice + cpu2Sys;
workOver = cpu2Work - cpu1Work;
totalOver = cpu2Total - cpu1Total;
cpuTotal = workOver / totalOver * 100;
printf("Cpu Idle : %ld \n", cpuTotal);
return 0;
}
The variables in your division are declared as integers. The problem is if you divide two integers, you will not get a fractional value. This means if the denominator is > than the numerator, the result will be 0.
Integer division does not automatically produce a floating point result.
To fix this, you can redeclare at least one of your variables in the formula as a float, or even cast them in the calculation.