Xinqi Bao's Git

d4f80647191e8117dc3ea589dba04981d4b748e3
[slstatus.git] / components / cpu.c
1 /* See LICENSE file for copyright and license details. */
2 #include <stdint.h>
3 #include <stdio.h>
4 #include <string.h>
5
6 #include "../util.h"
7
8 #if defined(__linux__)
9 const char *
10 cpu_freq(void)
11 {
12 uintmax_t freq;
13
14 /* in kHz */
15 if (pscanf("/sys/devices/system/cpu/cpu0/cpufreq/"
16 "scaling_cur_freq", "%ju", &freq) != 1) {
17 return NULL;
18 }
19
20 return fmt_human(freq * 1000, 1000);
21 }
22
23 const char *
24 cpu_perc(void)
25 {
26 static long double a[7];
27 long double b[7];
28
29 memcpy(b, a, sizeof(b));
30 /* cpu user nice system idle iowait irq softirq */
31 if (pscanf("/proc/stat", "%*s %Lf %Lf %Lf %Lf %Lf %Lf %Lf",
32 &a[0], &a[1], &a[2], &a[3], &a[4], &a[5], &a[6])
33 != 7) {
34 return NULL;
35 }
36 if (b[0] == 0) {
37 return NULL;
38 }
39
40 return bprintf("%d", (int)(100 *
41 ((b[0] + b[1] + b[2] + b[5] + b[6]) -
42 (a[0] + a[1] + a[2] + a[5] + a[6])) /
43 ((b[0] + b[1] + b[2] + b[3] + b[4] + b[5] +
44 b[6]) -
45 (a[0] + a[1] + a[2] + a[3] + a[4] + a[5] +
46 a[6]))));
47 }
48 #elif defined(__OpenBSD__)
49 #include <sys/param.h>
50 #include <sys/sched.h>
51 #include <sys/sysctl.h>
52
53 const char *
54 cpu_freq(void)
55 {
56 int mib[2];
57 uintmax_t freq;
58 size_t size;
59
60 mib[0] = CTL_HW;
61 mib[1] = HW_CPUSPEED;
62
63 size = sizeof(freq);
64
65 /* in MHz */
66 if (sysctl(mib, 2, &freq, &size, NULL, 0) < 0) {
67 warn("sysctl 'HW_CPUSPEED':");
68 return NULL;
69 }
70
71 return fmt_human(freq * 1E6, 1000);
72 }
73
74 const char *
75 cpu_perc(void)
76 {
77 int mib[2];
78 static uintmax_t a[CPUSTATES];
79 uintmax_t b[CPUSTATES];
80 size_t size;
81
82 mib[0] = CTL_KERN;
83 mib[1] = KERN_CPTIME;
84
85 size = sizeof(a);
86
87 memcpy(b, a, sizeof(b));
88 if (sysctl(mib, 2, &a, &size, NULL, 0) < 0) {
89 warn("sysctl 'KERN_CPTIME':");
90 return NULL;
91 }
92 if (b[0] == 0) {
93 return NULL;
94 }
95
96 return bprintf("%d", 100 *
97 ((a[CP_USER] + a[CP_NICE] + a[CP_SYS] +
98 a[CP_INTR]) -
99 (b[CP_USER] + b[CP_NICE] + b[CP_SYS] +
100 b[CP_INTR])) /
101 ((a[CP_USER] + a[CP_NICE] + a[CP_SYS] +
102 a[CP_INTR] + a[CP_IDLE]) -
103 (b[CP_USER] + b[CP_NICE] + b[CP_SYS] +
104 b[CP_INTR] + b[CP_IDLE])));
105 }
106 #endif