我正在用 C 编写一个小程序,它将在 1 秒内输出 CPU 使用率的总百分比。我已经让它大部分工作了,它确实计算了正确的数字,但最终计算将 workOver 除以 totalOver * 100 它总是输出 0。我不知道为什么。任何帮助都会很棒。代码如下。
#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;
}