1 // vim:sw=8:sts=8:ts=8:expandtab
9 static int prev_total = 0;
10 static int prev_idle = 0;
13 * Reads the CPU utilization from /proc/stat and returns the usage as a
17 void print_cpu_usage(const char *format) {
20 int curr_user, curr_nice, curr_system, curr_idle, curr_total;
21 int diff_idle, diff_total, diff_usage;
24 static char statpath[512];
25 strcpy(statpath, "/proc/stat");
26 if (!slurp(statpath, buf, sizeof(buf)))
27 die("could not read %s\n", statpath);
29 if (sscanf(buf, "cpu %d %d %d %d", &curr_user, &curr_nice, &curr_system, &curr_idle) != 4)
30 die("could not read cpu utilization\n");
32 curr_total = curr_user + curr_nice + curr_system + curr_idle;
33 diff_idle = curr_idle - prev_idle;
34 diff_total = curr_total - prev_total;
35 diff_usage = (1000 * (diff_total - diff_idle)/diff_total + 5)/10;
36 prev_total = curr_total;
37 prev_idle = curr_idle;
39 for (walk = format; *walk != '\0'; walk++) {
45 if (strncmp(walk+1, "usage", strlen("usage")) == 0) {
46 printf("%02d%%", diff_usage);
47 walk += strlen("usage");