utils

tiny programs I use on my system
Download | Log | Files | Refs | README | LICENSE

sb-cpu.c (1189B)


      1 #include <stdio.h>
      2 #include <unistd.h>
      3 
      4 typedef struct {
      5   long long idle;
      6   long long total;
      7 } cpu_stats_t;
      8 
      9 static int read_cpu_stats(cpu_stats_t *stats) {
     10   FILE *fp = fopen("/proc/stat", "r");
     11   if (!fp)
     12     return 1;
     13 
     14   long long user, nice, system, idle, iowait, irq, softirq;
     15   int ret = fscanf(fp, "cpu %lld %lld %lld %lld %lld %lld %lld", &user, &nice,
     16                    &system, &idle, &iowait, &irq, &softirq);
     17   fclose(fp);
     18 
     19   if (ret != 7)
     20     return 1;
     21 
     22   stats->idle = idle + iowait;
     23   stats->total = user + nice + system + idle + iowait + irq + softirq;
     24   return 0;
     25 }
     26 
     27 static double calculate_usage(cpu_stats_t *prev, cpu_stats_t *curr) {
     28   long long diff_total = curr->total - prev->total;
     29   long long diff_idle = curr->idle - prev->idle;
     30 
     31   if (diff_total == 0)
     32     return 0.0;
     33   return 100.0 * (diff_total - diff_idle) / diff_total;
     34 }
     35 
     36 int main() {
     37   cpu_stats_t prev, curr;
     38 
     39   if (read_cpu_stats(&prev) < 0) {
     40     fprintf(stderr, "Error reading CPU stats\n");
     41     return 1;
     42   }
     43 
     44   sleep(1);
     45 
     46   if (read_cpu_stats(&curr) < 0) {
     47     fprintf(stderr, "Error reading CPU stats\n");
     48     return 1;
     49   }
     50 
     51   printf("CPU: %.0f%%\n", calculate_usage(&prev, &curr));
     52   return 0;
     53 }