Hello!
I have some interest in determining cpu load in run-time, but have no
idea how to implement this.
Printable View
Hello!
I have some interest in determining cpu load in run-time, but have no
idea how to implement this.
man getloadavg
This is a part from one of my functions. I've corrected it slightly but I hope it will be clear for you.Code:
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);
Thanks all!
It seems with some #ifdef's and your samples I can forge cross-platform solution for problem.