Xinqi Bao's Git

Remove unnecessary "valid" variable in cpu_perc
[slstatus.git] / components / cpu.c
1 /* See LICENSE file for copyright and license details. */
2 #include <errno.h>
3 #include <stdio.h>
4 #include <string.h>
5
6 #include "../util.h"
7
8 #if defined(__linux__)
9 #include <inttypes.h>
10 #include <stdint.h>
11
12 const char *
13 cpu_freq(void)
14 {
15 uint64_t freq;
16
17 /* in kHz */
18 if (pscanf("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq",
19 "%"SCNu64, &freq) != 1) {
20 return NULL;
21 }
22
23 return fmt_human_10(freq * 1000, "Hz");
24 }
25
26 const char *
27 cpu_perc(void)
28 {
29 static long double a[7];
30 long double b[7];
31
32 memcpy(b, a, sizeof(b));
33 /* cpu user nice system idle iowait irq softirq */
34 if (pscanf("/proc/stat", "%*s %Lf %Lf %Lf %Lf %Lf %Lf %Lf",
35 &a[0], &a[1], &a[2], &a[3], &a[4], &a[5], &a[6]) != 7) {
36 return NULL;
37 }
38 if (b[0] == 0) {
39 return NULL;
40 }
41
42 return bprintf("%d%%", (int)(100 *
43 ((b[0] + b[1] + b[2] + b[5] + b[6]) -
44 (a[0] + a[1] + a[2] + a[5] + a[6])) /
45 ((b[0] + b[1] + b[2] + b[3] + b[4] + b[5] + b[6]) -
46 (a[0] + a[1] + a[2] + a[3] + a[4] + a[5] + 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 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_10((size_t)freq * 1000 * 1000, "Hz");
71 }
72
73 const char *
74 cpu_perc(void)
75 {
76 int mib[2];
77 static long int a[CPUSTATES];
78 long int 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