Xinqi Bao's Git

Revert component-split
[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 #if defined(__OpenBSD__)
6 #include <sys/sysctl.h>
7 #endif
8
9 #include "../util.h"
10
11 #if defined(__linux__)
12 const char *
13 cpu_freq(void)
14 {
15 int freq;
16
17 return (pscanf("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq",
18 "%i", &freq) == 1) ?
19 bprintf("%d", (freq + 500) / 1000) : NULL;
20 }
21
22 const char *
23 cpu_perc(void)
24 {
25 int perc;
26 static long double a[7];
27 static int valid;
28 long double b[7];
29
30 memcpy(b, a, sizeof(b));
31 if (pscanf("/proc/stat", "%*s %Lf %Lf %Lf %Lf %Lf %Lf %Lf", &a[0], &a[1], &a[2],
32 &a[3], &a[4], &a[5], &a[6]) != 7) {
33 return NULL;
34 }
35 if (!valid) {
36 valid = 1;
37 return NULL;
38 }
39
40 perc = 100 * ((b[0]+b[1]+b[2]+b[5]+b[6]) - (a[0]+a[1]+a[2]+a[5]+a[6])) /
41 ((b[0]+b[1]+b[2]+b[3]+b[4]+b[5]+b[6]) - (a[0]+a[1]+a[2]+a[3]+a[4]+a[5]+a[6]));
42
43 return bprintf("%d", perc);
44 }
45
46 const char *
47 cpu_iowait(void)
48 {
49 int perc;
50 static int valid;
51 static long double a[7];
52 long double b[7];
53
54 memcpy(b, a, sizeof(b));
55 if (pscanf("/proc/stat", "%*s %Lf %Lf %Lf %Lf %Lf %Lf %Lf", &a[0], &a[1], &a[2],
56 &a[3], &a[4], &a[5], &a[6]) != 7) {
57 return NULL;
58 }
59 if (!valid) {
60 valid = 1;
61 return NULL;
62 }
63
64 perc = 100 * ((b[4]) - (a[4])) /
65 ((b[0]+b[1]+b[2]+b[3]+b[4]+b[5]+b[6]) - (a[0]+a[1]+a[2]+a[3]+a[4]+a[5]+a[6]));
66
67 return bprintf("%d", perc);
68 }
69 #elif defined(__OpenBSD__)
70 const char *
71 cpu_freq(void)
72 {
73 int freq, mib[2];
74 size_t size;
75
76 mib[0] = CTL_HW;
77 mib[1] = HW_CPUSPEED;
78
79 size = sizeof(freq);
80
81 if (sysctl(mib, 2, &freq, &size, NULL, 0) == -1) {
82 fprintf(stderr, "sysctl 'HW_CPUSPEED': %s\n", strerror(errno));
83 return NULL;
84 }
85
86 return bprintf("%d", freq);
87 }
88 #endif