355f6bbc96a160617ad04d62f4765d333f161fa1
[sysstatus.git] / statuses / cpuusage.c
1 #include <stdio.h>
2 #include <fcntl.h>
3 #include <unistd.h>
4 #include <stdlib.h>
5 #include "cpuusage.h"
6 #include "../config.h"
7
8 #ifndef NUM_CPUS
9   #define NUM_CPUS 1
10 #endif
11 #ifndef CPU_HISTORY_SIZE
12   #define CPU_HISTORY_SIZE 1
13 #endif
14 #if CPU_HISTORY_SIZE < 1
15   #define CPU_HISTORY_SIZE 1
16 #endif
17
18
19 unsigned long last_cpu_used = 0;
20 unsigned long last_cpu_total = 0;
21 float cpu_history[CPU_HISTORY_SIZE]; // don't care about init values
22
23 void status_cpuusage()
24 {
25   double loadavg[3] = { -13.37, -13.37, -13.37 } ;
26
27   char *stline = NULL;
28   size_t stlen;
29   FILE *stfile;
30
31   unsigned long cpu_user;
32   unsigned long cpu_nice;
33   unsigned long cpu_sys;
34   unsigned long cpu_used;
35   unsigned long cpu_idle;
36   unsigned long cpu_total;
37   int i;
38
39
40   // Error signaling color
41   fputs("^fg(yellow)", stdout);
42
43   stfile = fopen("/proc/stat", "r");
44   if (stfile != NULL) {
45     for(i = CPU_HISTORY_SIZE - 1; i > 0; i--) {
46       cpu_history[i] = cpu_history[i - 1];
47     }
48
49     stlen = getline(&stline, &stlen, stfile);
50     fclose(stfile);
51
52     if ( 4 == sscanf(stline, "%*s %ld %ld %ld %ld",
53                     &cpu_user, &cpu_nice, &cpu_sys, &cpu_idle) ) {
54       cpu_used = cpu_user + cpu_nice + cpu_sys;
55       cpu_total = cpu_used + cpu_idle;
56
57       // Now do the percentage
58       cpu_history[0] = (float)(cpu_used - last_cpu_used) /
59                         (float)(cpu_total - last_cpu_total);
60
61       last_cpu_used = cpu_used;
62       last_cpu_total = cpu_total;
63
64
65       if (cpu_history[0] < 0.4) {
66         // CPU idling OK
67         fputs("^fg(#0077FF)", stdout);
68       } else {
69         // CPU busy
70         fputs("^fg(#FF00FF)", stdout);
71       }
72
73       //printf(" CPU: %.0f%% ", cpu_history[0] * 100);
74     }
75
76     free(stline);
77   }
78
79
80   if (getloadavg(loadavg, 3) > 0) {
81     printf(" %s%.0f,%.0f,%.0f,%.0f ",
82             cpu_history[0] < 0.1000 ? " " : "",
83             cpu_history[0] * 100,
84             loadavg[0] * (100 / 1),
85             loadavg[1] * (100 / 1),  // (100 / NUM_CPUS)
86             loadavg[2] * (100 / 1));
87   }
88
89   //fputs(" CPU usage ", stdout);
90 }