gettimeofday(2) can be used to calculate the CPU usage from "/proc/
stat". But it isn't useful when you only want to calculate the CPU
usage of some processes.
* * *
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
double time_so_far()
{
struct timeval tp;
if (gettimeofday(&tp, (struct timezone *) NULL) == -1)
perror("gettimeofday");
return ((double) (tp.tv_sec)) +
(((double) tp.tv_usec) * 0.000001 );
}
int main() {
FILE *f1;
double ti, tf;
char c[10];
int i1,i2,i3,i4,i5,i6;
ti = time_so_far();
f1 = fopen("/proc/stat", "r");
fscanf(f1, "%s\t%d\t%d\t%d\n", c, &i1, &i2, &i3);
fclose(f1);
usleep(1000000);
tf = time_so_far();
f1 = fopen("/proc/stat", "r");
fscanf(f1, "%s\t%d\t%d\t%d\n", c, &i4, &i5, &i6);
fclose(f1);
int t = (i4+i5+i6)-(i1+i2+i3);
printf("cpu usage: %.1f%%\n", (t / ((tf-ti) * 100)) * 100);
return 0;
}
* * *
To calculate the CPU usage of some processes it's necessary to get
some fields expressed in number of CPU ticks. And as is said in
times(2) [2]:
"the number of clock ticks per second can be obtained using:
sysconf(_SC_CLK_TCK);"
So, can it get the value of "_SC_CLK_TCK" in package syscall? If no,
please add it, from it's necessary to read (interpret) values in /proc/
stat
[1]:
http://www.linuxquestions.org/questions/programming-9/proc-stat-file-problem-for-cpu-usage-369302/
[2]:
http://www.kernel.org/doc/man-pages/online/pages/man2/times.2.html