]> git.sur5r.net Git - i3/i3status/blob - src/print_cpu_usage.c
d97a7fa303a3c50bcf2226633ffaafa5cb4644c8
[i3/i3status] / src / print_cpu_usage.c
1 // vim:sw=8:sts=8:ts=8:expandtab
2 #include <stdlib.h>
3 #include <limits.h>
4 #include <stdio.h>
5 #include <string.h>
6
7 #ifdef __FreeBSD__
8 #include <sys/types.h>
9 #include <sys/sysctl.h>
10 #include <sys/dkstat.h>
11 #endif
12
13 #include "i3status.h"
14
15 static int prev_total = 0;
16 static int prev_idle  = 0;
17
18 /*
19  * Reads the CPU utilization from /proc/stat and returns the usage as a
20  * percentage.
21  *
22  */
23 void print_cpu_usage(const char *format) {
24         const char *walk;
25         char buf[1024];
26         int curr_user = 0, curr_nice = 0, curr_system = 0, curr_idle = 0, curr_total;
27         int diff_idle, diff_total, diff_usage;
28
29         if (output_format == O_I3BAR)
30                 printf("{\"name\":\"cpu_usage\", \"full_text\":\"");
31
32 #if defined(LINUX)
33         static char statpath[512];
34         strcpy(statpath, "/proc/stat");
35         if (!slurp(statpath, buf, sizeof(buf)) ||
36             sscanf(buf, "cpu %d %d %d %d", &curr_user, &curr_nice, &curr_system, &curr_idle) != 4)
37                 goto error;
38
39         curr_total = curr_user + curr_nice + curr_system + curr_idle;
40         diff_idle  = curr_idle - prev_idle;
41         diff_total = curr_total - prev_total;
42         diff_usage = (1000 * (diff_total - diff_idle)/diff_total + 5)/10;
43         prev_total = curr_total;
44         prev_idle  = curr_idle;
45 #elif defined(__FreeBSD__)
46         size_t size;
47         long cp_time[CPUSTATES];
48         size = sizeof cp_time;
49         if (sysctlbyname("kern.cp_time", &cp_time, &size, NULL, 0) < 0)
50                 goto error;
51
52         curr_user = cp_time[CP_USER];
53         curr_nice = cp_time[CP_NICE];
54         curr_system = cp_time[CP_SYS];
55         curr_idle = cp_time[CP_IDLE];
56         curr_total = curr_user + curr_nice + curr_system + curr_idle;
57         diff_idle  = curr_idle - prev_idle;
58         diff_total = curr_total - prev_total;
59         diff_usage = (1000 * (diff_total - diff_idle)/diff_total + 5)/10;
60         prev_total = curr_total;
61         prev_idle  = curr_idle;
62 #else
63         goto error;
64 #endif
65         for (walk = format; *walk != '\0'; walk++) {
66                 if (*walk != '%') {
67                         putchar(*walk);
68                         continue;
69                 }
70
71                 if (strncmp(walk+1, "usage", strlen("usage")) == 0) {
72                         printf("%02d%%", diff_usage);
73                         walk += strlen("usage");
74                 }
75         }
76
77         if (output_format == O_I3BAR)
78                 printf("\"}");
79
80         return;
81 error:
82         (void)fputs("Cannot read usage\n", stderr);
83 }