1 // vim:sw=8:sts=8:ts=8:expandtab
6 #include <yajl/yajl_gen.h>
10 #include <sys/sysctl.h>
11 #include <sys/dkstat.h>
16 static int prev_total = 0;
17 static int prev_idle = 0;
20 * Reads the CPU utilization from /proc/stat and returns the usage as a
24 void print_cpu_usage(yajl_gen json_gen, char *buffer, const char *format) {
26 char *outwalk = buffer;
28 int curr_user = 0, curr_nice = 0, curr_system = 0, curr_idle = 0, curr_total;
29 int diff_idle, diff_total, diff_usage;
32 static char statpath[512];
33 strcpy(statpath, "/proc/stat");
34 if (!slurp(statpath, buf, sizeof(buf)) ||
35 sscanf(buf, "cpu %d %d %d %d", &curr_user, &curr_nice, &curr_system, &curr_idle) != 4)
38 curr_total = curr_user + curr_nice + curr_system + curr_idle;
39 diff_idle = curr_idle - prev_idle;
40 diff_total = curr_total - prev_total;
41 diff_usage = (1000 * (diff_total - diff_idle)/diff_total + 5)/10;
42 prev_total = curr_total;
43 prev_idle = curr_idle;
44 #elif defined(__FreeBSD__)
46 long cp_time[CPUSTATES];
47 size = sizeof cp_time;
48 if (sysctlbyname("kern.cp_time", &cp_time, &size, NULL, 0) < 0)
51 curr_user = cp_time[CP_USER];
52 curr_nice = cp_time[CP_NICE];
53 curr_system = cp_time[CP_SYS];
54 curr_idle = cp_time[CP_IDLE];
55 curr_total = curr_user + curr_nice + curr_system + curr_idle;
56 diff_idle = curr_idle - prev_idle;
57 diff_total = curr_total - prev_total;
58 diff_usage = (1000 * (diff_total - diff_idle)/diff_total + 5)/10;
59 prev_total = curr_total;
60 prev_idle = curr_idle;
64 for (walk = format; *walk != '\0'; walk++) {
70 if (strncmp(walk+1, "usage", strlen("usage")) == 0) {
71 outwalk += sprintf(outwalk, "%02d%%", diff_usage);
72 walk += strlen("usage");
76 OUTPUT_FULL_TEXT(buffer);
79 (void)fputs("Cannot read usage\n", stderr);