typedef struct CPU_OCCUPY_//defines the structure of a CPU occupy {char name[20];//defines an array name for a char type name has 20 elements unsigned int user;//define an unsigned I NT type user unsigned int nice; Defines a nice unsigned int system with an unsigned int type; Defines an unsigned int type of system unsigned int idle; Defines an unsigned int of type idle unsigned int iowait; unsigned int IRQ; unsigned int softirq;} Cpu_occupy_t;double cal_cpuoccupy (cpu_occupy_t *o, cpu_occupy_t *n) {double od, ND; double ID, SD; double cpu_use; od = (double) (O->user + o->nice + o->system +O->IDLE+O->SOFTIRQ+O->IOWAIT+O->IRQ);//First time (user + priority + system + Idle) The time is then assigned to od nd = (double) (N->user + n->nice + n->system +N->IDLE+N->SOFTIRQ+N->IOWAIT+N->IRQ);//second ( User + priority + System + Idle time is then assigned to OD id = (double) (n->idle); The user's first and second time difference is assigned to the ID SD = (double) (o->idle); The difference between the first and second times of the system is then assigned to the SD if ((nd-od)! = 0) Cpu_use =100.0-((ID-SD))/(Nd-od) *100.00; (user + system) good 100) in addition to (the first and second time difference) is assigned to g_cpu_used else Cpu_use = 0; return cpu_use;} void Get_cpuoccupy (cpu_occupy_t *cpust) {FILE *fd; int n; char bUFF[256]; cpu_occupy_t *cpu_occupy; Cpu_occupy=cpust; FD = fopen ("/proc/stat", "R"); if (fd = = NULL) {perror ("fopen:"); Exit (0); } fgets (buff, sizeof (buff), FD); SSCANF (Buff, "%s%u%u%u,%u,%u%u%u", Cpu_occupy->name, &cpu_occupy->user, &cpu_occupy->nice,&cpu_ Occupy->system, &cpu_occupy->idle, &cpu_occupy->iowait,&cpu_occupy->irq,&cpu_occupy- >SOFTIRQ); Fclose (FD);} Double Get_syscpuusage () {cpu_occupy_t cpu_stat1; cpu_occupy_t cpu_stat2; double cpu; Get_cpuoccupy ((cpu_occupy_t *) &CPU_STAT1); Sleep (1); Second acquisition of CPU usage get_cpuoccupy ((cpu_occupy_t *) &CPU_STAT2); Compute CPU Utilization CPU = Cal_cpuoccupy ((cpu_occupy_t *) &CPU_STAT1, (cpu_occupy_t *) &CPU_STAT2); return CPU;}
Get System CPU Usage (Linux C)