]> git.sur5r.net Git - i3/i3status/blob - src/print_cpu_usage.c
fix parentheses in cc1457c4f0f4cccb8bec326dd0bb13082ac806e6
[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 defined(LINUX)
30         static char statpath[512];
31         strcpy(statpath, "/proc/stat");
32         if (!slurp(statpath, buf, sizeof(buf)) ||
33             sscanf(buf, "cpu %d %d %d %d", &curr_user, &curr_nice, &curr_system, &curr_idle) != 4)
34                 goto error;
35
36         curr_total = curr_user + curr_nice + curr_system + curr_idle;
37         diff_idle  = curr_idle - prev_idle;
38         diff_total = curr_total - prev_total;
39         diff_usage = (1000 * (diff_total - diff_idle)/diff_total + 5)/10;
40         prev_total = curr_total;
41         prev_idle  = curr_idle;
42 #elif defined(__FreeBSD__)
43         size_t size;
44         long cp_time[CPUSTATES];
45         size = sizeof cp_time;
46         if (sysctlbyname("kern.cp_time", &cp_time, &size, NULL, 0) < 0)
47                 goto error;
48
49         curr_user = cp_time[CP_USER];
50         curr_nice = cp_time[CP_NICE];
51         curr_system = cp_time[CP_SYS];
52         curr_idle = cp_time[CP_IDLE];
53         curr_total = curr_user + curr_nice + curr_system + curr_idle;
54         diff_idle  = curr_idle - prev_idle;
55         diff_total = curr_total - prev_total;
56         diff_usage = (1000 * (diff_total - diff_idle)/diff_total + 5)/10;
57         prev_total = curr_total;
58         prev_idle  = curr_idle;
59 #else
60         goto error;
61 #endif
62         for (walk = format; *walk != '\0'; walk++) {
63                 if (*walk != '%') {
64                         putchar(*walk);
65                         continue;
66                 }
67
68                 if (strncmp(walk+1, "usage", strlen("usage")) == 0) {
69                         printf("%02d%%", diff_usage);
70                         walk += strlen("usage");
71                 }
72         }
73         return;
74 error:
75         (void)fputs("Cannot read usage\n", stderr);
76 }