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