Created
December 16, 2021 07:19
-
-
Save ardabbour/8a4497480023dfdfda6cd790b08c3048 to your computer and use it in GitHub Desktop.
very unoptimized way of calculating the cpu usage percentage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <unistd.h> | |
struct cpu_data_t { | |
int user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice; | |
}; | |
// based on answer here: https://stackoverflow.com/a/23376195/8295404 | |
float calculate_cpu_percentage(struct cpu_data_t prev, struct cpu_data_t curr) { | |
float PrevIdle = prev.idle + prev.iowait; | |
float Idle = curr.idle + curr.iowait; | |
float PrevNonIdle = prev.user + prev.nice + prev.system + prev.irq + | |
prev.softirq + prev.steal; | |
float NonIdle = curr.user + curr.nice + curr.system + curr.irq + | |
curr.softirq + curr.steal; | |
float PrevTotal = PrevIdle + PrevNonIdle; | |
float Total = Idle + NonIdle; | |
float totald = Total - PrevTotal; | |
float idled = Idle - PrevIdle; | |
return (totald - idled) / totald; | |
} | |
struct cpu_data_t get_cpu_data() { | |
struct cpu_data_t cpu_data; | |
FILE *fp; | |
char *line = NULL; | |
size_t len = 0; | |
fp = fopen("/proc/stat", "r"); | |
if (fp == NULL) { | |
exit(EXIT_FAILURE); | |
} | |
while (getline(&line, &len, fp) != -1) { | |
char *pch = strtok(line, " ,.-"); | |
int value = strcmp("cpu", pch); | |
if (value == 0) { | |
pch = strtok(NULL, " ,.-"); | |
for (int i = 0; i < 10; ++i) { | |
if (i == 0) { | |
cpu_data.user = atof(pch); | |
} | |
if (i == 1) { | |
cpu_data.nice = atof(pch); | |
} | |
if (i == 2) { | |
cpu_data.system = atof(pch); | |
} | |
if (i == 3) { | |
cpu_data.idle = atof(pch); | |
} | |
if (i == 4) { | |
cpu_data.iowait = atof(pch); | |
} | |
if (i == 5) { | |
cpu_data.irq = atof(pch); | |
} | |
if (i == 6) { | |
cpu_data.softirq = atof(pch); | |
} | |
if (i == 7) { | |
cpu_data.steal = atof(pch); | |
} | |
if (i == 8) { | |
cpu_data.guest = atof(pch); | |
} | |
if (i == 9) { | |
cpu_data.guest_nice = atof(pch); | |
} | |
// printf("%s\n", pch); | |
pch = strtok(NULL, " ,.-"); | |
} | |
} | |
} | |
fclose(fp); | |
if (line) { | |
free(line); | |
} | |
return cpu_data; | |
} | |
int main(void) { | |
struct cpu_data_t prev, curr; | |
prev = get_cpu_data(); | |
usleep(1100000); | |
curr = get_cpu_data(); | |
while (1) { | |
float cpu_percentage = calculate_cpu_percentage(prev, curr); | |
printf("current cpu usage: %f\n", cpu_percentage * 100); | |
prev = get_cpu_data(); | |
usleep(1100000); | |
curr = get_cpu_data(); | |
} | |
exit(EXIT_SUCCESS); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment