cpu_perc: Port to OpenBSD
authorAaron Marcher <me@drkhsh.at>
Sun, 6 May 2018 15:48:37 +0000 (17:48 +0200)
committerAaron Marcher <me@drkhsh.at>
Sun, 6 May 2018 15:48:37 +0000 (17:48 +0200)
In OpenBSD the CPU usage in percent is now computed using KERN_CPTIME
sysctl.

README
components/cpu.c

diff --git a/README b/README
index 096103036c295f874e58439100ea5fdd3716aef3..805f541ec468d28f3f553d1e7afc3b7a61cabb1d 100644 (file)
--- a/README
+++ b/README
@@ -62,5 +62,5 @@ Porting to OpenBSD is the current goal before thinking about a release.
 
 The following functions are not portable at the moment:
 - wifi_{perc,essid}
-- cpu_{perc,iowait}
+- cpu_iowait
 - entropy
index e7f4cd9d14c537fea8740e9cfc68c8a8766cd51d..79bb881d1b4c86caf9c05ac9a6d2d9c4e5755f68 100644 (file)
@@ -68,6 +68,8 @@
                return bprintf("%d", perc);
        }
 #elif defined(__OpenBSD__)
+       #include <sys/param.h>
+       #include <sys/sched.h>
        #include <sys/sysctl.h>
 
        const char *
 
                return bprintf("%d", freq);
        }
+
+       const char *
+       cpu_perc(void)
+       {
+               int mib[2], perc;
+               static int valid;
+               static long int a[CPUSTATES];
+               long int b[CPUSTATES];
+               size_t size;
+
+               mib[0] = CTL_KERN;
+               mib[1] = KERN_CPTIME;
+
+               size = sizeof(a);
+
+               memcpy(b, a, sizeof(b));
+               if (sysctl(mib, 2, &a, &size, NULL, 0) == -1) {
+                       fprintf(stderr, "sysctl 'KERN_CPTIME': %s\n", strerror(errno));
+                       return NULL;
+               }
+               if (!valid) {
+                       valid = 1;
+                       return NULL;
+               }
+
+               perc = 100 *
+                      ((a[CP_USER]+a[CP_NICE]+a[CP_SYS]+a[CP_INTR]) -
+                       (b[CP_USER]+b[CP_NICE]+b[CP_SYS]+b[CP_INTR])) /
+                      ((a[CP_USER]+a[CP_NICE]+a[CP_SYS]+a[CP_INTR]+a[CP_IDLE]) -
+                       (b[CP_USER]+b[CP_NICE]+b[CP_SYS]+b[CP_INTR]+b[CP_IDLE]));
+
+               return bprintf("%d", perc);
+       }
 #endif