Xinqi Bao's Git

uptime: Improve typing and sort headers
[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 uint64_t freq;
15
16 /* in kHz */
17 if (pscanf("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq",
18 "%"SCNu64, &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 <sys/param.h>
49 #include <sys/sched.h>
50 #include <sys/sysctl.h>
51
52 const char *
53 cpu_freq(void)
54 {
55 int freq, mib[2];
56 size_t size;
57
58 mib[0] = CTL_HW;
59 mib[1] = HW_CPUSPEED;
60
61 size = sizeof(freq);
62
63 /* in MHz */
64 if (sysctl(mib, 2, &freq, &size, NULL, 0) < 0) {
65 warn("sysctl 'HW_CPUSPEED':");
66 return NULL;
67 }
68
69 return fmt_human((size_t)freq * 1000 * 1000, 1000);
70 }
71
72 const char *
73 cpu_perc(void)
74 {
75 int mib[2];
76 static long int a[CPUSTATES];
77 long int b[CPUSTATES];
78 size_t size;
79
80 mib[0] = CTL_KERN;
81 mib[1] = KERN_CPTIME;
82
83 size = sizeof(a);
84
85 memcpy(b, a, sizeof(b));
86 if (sysctl(mib, 2, &a, &size, NULL, 0) < 0) {
87 warn("sysctl 'KERN_CPTIME':");
88 return NULL;
89 }
90 if (b[0] == 0) {
91 return NULL;
92 }
93
94 return bprintf("%d", 100 *
95 ((a[CP_USER] + a[CP_NICE] + a[CP_SYS] + a[CP_INTR]) -
96 (b[CP_USER] + b[CP_NICE] + b[CP_SYS] + b[CP_INTR])) /
97 ((a[CP_USER] + a[CP_NICE] + a[CP_SYS] + a[CP_INTR] +
98 a[CP_IDLE]) -
99 (b[CP_USER] + b[CP_NICE] + b[CP_SYS] + b[CP_INTR] +
100 b[CP_IDLE])));
101 }
102 #endif