I have tried using this program (adapted from this SO answer):
// First segment (down to L49) is from SO https://stackoverflow.com/a/26930298/1876983
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
using namespace std;
static unsigned long long lastTotalUser, lastTotalUserLow, lastTotalSys, lastTotalIdle;
void init(){
FILE* file = fopen("/proc/stat", "r");
fscanf(file, "cpu %llu %llu %llu %llu", &lastTotalUser, &lastTotalUserLow,
&lastTotalSys, &lastTotalIdle);
fclose(file);
}
double getCurrentValue(){
double percent;
FILE* file;
unsigned long long totalUser, totalUserLow, totalSys, totalIdle, total;
file = fopen("/proc/stat", "r");
fscanf(file, "cpu %llu %llu %llu %llu", &totalUser, &totalUserLow,
&totalSys, &totalIdle);
fclose(file);
if (totalUser < lastTotalUser || totalUserLow < lastTotalUserLow ||
totalSys < lastTotalSys || totalIdle < lastTotalIdle){
//Overflow detection. Just skip this value.
percent = -1.0;
}
else{
total = (totalUser - lastTotalUser) + (totalUserLow - lastTotalUserLow) +
(totalSys - lastTotalSys);
percent = total;
total += (totalIdle - lastTotalIdle);
percent /= total;
percent *= 100;
}
lastTotalUser = totalUser;
lastTotalUserLow = totalUserLow;
lastTotalSys = totalSys;
lastTotalIdle = totalIdle;
return percent;
}
int main() {
double CPU = getCurrentValue();
printf("%.2f", CPU);
return 0;
}
To determine current total CPU usage on Linux, but it seems to be determining average total CPU usage. At the moment the KDE CPU monitor is telling me my CPU usage is just 17% and this program tells me it is 60.19%. Now earlier today I was compiling a heap of software using the Portage package manager so the 60.19% seems to be more accurately represent my average CPU usage since I turned this PC on. This CPU usage figure has been going down since I stopped compiling software, further supporting the idea this is the average CPU usage, not the current CPU usage.