Xinqi Bao's Git

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