PDA

View Full Version : Any ideas on determining cpu load in run-time?



a550ee
23rd November 2006, 20:10
Hello!
I have some interest in determining cpu load in run-time, but have no
idea how to implement this.

wysota
23rd November 2006, 20:51
man getloadavg

Mad Max
24th November 2006, 04:16
FILE *file;
unsigned proc_count = 0;
long cpu = 0, nice = 0, system = 0, idle = 0, used = 0, total = 0;
char buff[MAXBUFF];
char *lpbuff = buff;
size_t n = 0;
char s_cpu_usage[MAXBUFF];

bzero(s_cpu_usage, MAXBUFF);
strcpy(s_cpu_usage, "");

proc_count = get_nprocs();

file = fopen("/proc/stat", "r");
if(!file)
{
sprintf(msg->error_str, "Error when getting CPU statistics. errno(%d) : %s", errno, strerror(errno));
return 0;
}
//
getline(&lpbuff, &n, file);
for (i = 0; i < proc_count; i++)
{
fscanf(file, "%*s %ld %ld %ld %ld", &cpu, &nice, &system, &idle);
used = cpu+nice+system;
total = cpu+nice+system+idle;

bzero(buff, MAXBUFF);
sprintf(lpbuff, "%ld %ld\n", used, total);
strcat(s_cpu_usage, lpbuff);
}
fclose(file);

This is a part from one of my functions. I've corrected it slightly but I hope it will be clear for you.

a550ee
24th November 2006, 09:38
Thanks all!
It seems with some #ifdef's and your samples I can forge cross-platform solution for problem.