I found this answer on StackOverflow for calculating total CPU usage: http://stackoverflow.com/questions/1420426/calculating-cpu-usage-of-a-process-in-linux/4497769#4497769
But how do I calculate that as a proportion of the total available CPU cycles? I'm trying to do it without having to spawn another process - just with syscalls and files.
I thought that number would just be the total
property of the information provided by glibtop_cpu
(as it seems to be user + nice + sys + idle
, but it actually changes over time.
I thought that might just be because the cycles will naturally vary from second to second, but in that case why does it report different numbers to top
? If I spawn a new tab in Firefox and load up a page, top
, shows Firefox using about 35% of one core for a couple of seconds - but the following code just shows a consistent 7.24%:
#include <stdio.h>
#include <time.h>
#include <glibtop/cpu.h>
#include <unistd.h>
float // Get CPU usge as a decimal percentage.
get_cpu(glibtop_cpu *cpustruct) {
glibtop_get_cpu(cpustruct);
return 100 - (float)cpustruct->idle / (float)cpustruct->total * 100;
}
int
main(void) {
glibtop_cpu cpustruct;
unsigned int sleepfor = 5000;
float usage;
for(;;usleep(sleepfor)) {
usage = get_cpu(&cpustruct);
printf("%.2f\n", usage);
}
exit(0);
}
top
command shows some processes using more than 50% of a CPU core. – Cerales Dec 27 '12 at 0:02