Xinqi Bao's Git

Simplify format specifiers for uintmax_t
[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/scaling_cur_freq",
16 "%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]) != 7) {
33 return NULL;
34 }
35 if (b[0] == 0) {
36 return NULL;
37 }
38
39 return bprintf("%d", (int)(100 *
40 ((b[0] + b[1] + b[2] + b[5] + b[6]) -
41 (a[0] + a[1] + a[2] + a[5] + a[6])) /
42 ((b[0] + b[1] + b[2] + b[3] + b[4] + b[5] + b[6]) -
43 (a[0] + a[1] + a[2] + a[3] + a[4] + a[5] + a[6]))));
44 }
45 #elif defined(__OpenBSD__)
46 #include <sys/param.h>
47 #include <sys/sched.h>
48 #include <sys/sysctl.h>
49
50 const char *
51 cpu_freq(void)
52 {
53 int mib[2];
54 uintmax_t freq;
55 size_t size;
56
57 mib[0] = CTL_HW;
58 mib[1] = HW_CPUSPEED;
59
60 size = sizeof(freq);
61
62 /* in MHz */
63 if (sysctl(mib, 2, &freq, &size, NULL, 0) < 0) {
64 warn("sysctl 'HW_CPUSPEED':");
65 return NULL;
66 }
67
68 return fmt_human(freq * 1E6, 1000);
69 }
70
71 const char *
72 cpu_perc(void)
73 {
74 int mib[2];
75 static uintmax_t a[CPUSTATES];
76 uintmax_t b[CPUSTATES];
77 size_t size;
78
79 mib[0] = CTL_KERN;
80 mib[1] = KERN_CPTIME;
81
82 size = sizeof(a);
83
84 memcpy(b, a, sizeof(b));
85 if (sysctl(mib, 2, &a, &size, NULL, 0) < 0) {
86 warn("sysctl 'KERN_CPTIME':");
87 return NULL;
88 }
89 if (b[0] == 0) {
90 return NULL;
91 }
92
93 return bprintf("%d", 100 *
94 ((a[CP_USER] + a[CP_NICE] + a[CP_SYS] + a[CP_INTR]) -
95 (b[CP_USER] + b[CP_NICE] + b[CP_SYS] + b[CP_INTR])) /
96 ((a[CP_USER] + a[CP_NICE] + a[CP_SYS] + a[CP_INTR] +
97 a[CP_IDLE]) -
98 (b[CP_USER] + b[CP_NICE] + b[CP_SYS] + b[CP_INTR] +
99 b[CP_IDLE])));
100 }
101 #endif