Xinqi Bao's Git

Remove cpu_iowait
[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 const char *
10 cpu_freq(void)
11 {
12 int freq;
13
14 return (pscanf("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq",
15 "%i", &freq) == 1) ?
16 bprintf("%d", (freq + 500) / 1000) : NULL;
17 }
18
19 const char *
20 cpu_perc(void)
21 {
22 int perc;
23 static long double a[7];
24 static int valid;
25 long double b[7];
26
27 memcpy(b, a, sizeof(b));
28 /* cpu user nice system idle iowait irq softirq */
29 if (pscanf("/proc/stat", "%*s %Lf %Lf %Lf %Lf %Lf %Lf %Lf",
30 &a[0], &a[1], &a[2], &a[3], &a[4], &a[5], &a[6]) != 7) {
31 return NULL;
32 }
33 if (!valid) {
34 valid = 1;
35 return NULL;
36 }
37
38 perc = 100 * ((b[0] + b[1] + b[2] + b[5] + b[6]) -
39 (a[0] + a[1] + a[2] + a[5] + a[6])) /
40 ((b[0] + b[1] + b[2] + b[3] + b[4] + b[5] + b[6]) -
41 (a[0] + a[1] + a[2] + a[3] + a[4] + a[5] + a[6]));
42
43 return bprintf("%d", perc);
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 freq, mib[2];
54 size_t size;
55
56 mib[0] = CTL_HW;
57 mib[1] = HW_CPUSPEED;
58
59 size = sizeof(freq);
60
61 if (sysctl(mib, 2, &freq, &size, NULL, 0) == -1) {
62 fprintf(stderr, "sysctl 'HW_CPUSPEED': %s\n",
63 strerror(errno));
64 return NULL;
65 }
66
67 return bprintf("%d", freq);
68 }
69
70 const char *
71 cpu_perc(void)
72 {
73 int mib[2], perc;
74 static int valid;
75 static long int a[CPUSTATES];
76 long int 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) == -1) {
86 fprintf(stderr, "sysctl 'KERN_CPTIME': %s\n", strerror(errno));
87 return NULL;
88 }
89 if (!valid) {
90 valid = 1;
91 return NULL;
92 }
93
94 perc = 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] + a[CP_IDLE]) -
98 (b[CP_USER] + b[CP_NICE] + b[CP_SYS] + b[CP_INTR] + b[CP_IDLE]));
99
100 return bprintf("%d", perc);
101 }
102 #endif