1 // vim:sw=8:sts=8:ts=8:expandtab
9 #include <sys/sysctl.h>
10 #include <sys/dkstat.h>
15 static int prev_total = 0;
16 static int prev_idle = 0;
19 * Reads the CPU utilization from /proc/stat and returns the usage as a
23 void print_cpu_usage(const char *format) {
26 int curr_user = 0, curr_nice = 0, curr_system = 0, curr_idle = 0, curr_total;
27 int diff_idle, diff_total, diff_usage;
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)
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__)
44 long cp_time[CPUSTATES];
45 size = sizeof cp_time;
46 if (sysctlbyname("kern.cp_time", &cp_time, &size, NULL, 0) < 0)
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;
62 for (walk = format; *walk != '\0'; walk++) {
68 if (strncmp(walk+1, "usage", strlen("usage")) == 0) {
69 printf("%02d%%", diff_usage);
70 walk += strlen("usage");
75 (void)fputs("Cannot read usage\n", stderr);