54 lines
1.2 KiB
C
54 lines
1.2 KiB
C
#include <stdio.h>
|
|
#include <unistd.h>
|
|
|
|
typedef struct {
|
|
long long idle;
|
|
long long total;
|
|
} cpu_stats_t;
|
|
|
|
static int read_cpu_stats(cpu_stats_t *stats) {
|
|
FILE *fp = fopen("/proc/stat", "r");
|
|
if (!fp)
|
|
return 1;
|
|
|
|
long long user, nice, system, idle, iowait, irq, softirq;
|
|
int ret = fscanf(fp, "cpu %lld %lld %lld %lld %lld %lld %lld", &user, &nice,
|
|
&system, &idle, &iowait, &irq, &softirq);
|
|
fclose(fp);
|
|
|
|
if (ret != 7)
|
|
return 1;
|
|
|
|
stats->idle = idle + iowait;
|
|
stats->total = user + nice + system + idle + iowait + irq + softirq;
|
|
return 0;
|
|
}
|
|
|
|
static double calculate_usage(cpu_stats_t *prev, cpu_stats_t *curr) {
|
|
long long diff_total = curr->total - prev->total;
|
|
long long diff_idle = curr->idle - prev->idle;
|
|
|
|
if (diff_total == 0)
|
|
return 0.0;
|
|
return 100.0 * (diff_total - diff_idle) / diff_total;
|
|
}
|
|
|
|
int main() {
|
|
cpu_stats_t prev, curr;
|
|
|
|
if (read_cpu_stats(&prev) < 0) {
|
|
fprintf(stderr, "Error reading CPU stats\n");
|
|
return 1;
|
|
}
|
|
|
|
sleep(1);
|
|
|
|
if (read_cpu_stats(&curr) < 0) {
|
|
fprintf(stderr, "Error reading CPU stats\n");
|
|
return 1;
|
|
}
|
|
|
|
printf("CPU: %.0f%%\n", calculate_usage(&prev, &curr));
|
|
return 0;
|
|
}
|