Xinqi Bao's Git

e333f97e52ee915fc073481194ec3b3354e658e7
[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 "%d", &freq) == 1) ?
16 bprintf("%d", (freq + 500) / 1000) : NULL;
17 }
18
19 const char *
20 cpu_perc(void)
21 {
22 static int valid;
23 static long double a[7];
24 long double b[7];
25
26 memcpy(b, a, sizeof(b));
27 /* cpu user nice system idle iowait irq softirq */
28 if (pscanf("/proc/stat", "%*s %Lf %Lf %Lf %Lf %Lf %Lf %Lf",
29 &a[0], &a[1], &a[2], &a[3], &a[4], &a[5], &a[6]) != 7) {
30 return NULL;
31 }
32 if (!valid) {
33 valid = 1;
34 return NULL;
35 }
36
37 return bprintf("%d%%", (int)(100 *
38 ((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 #elif defined(__OpenBSD__)
44 #include <sys/param.h>
45 #include <sys/sched.h>
46 #include <sys/sysctl.h>
47
48 const char *
49 cpu_freq(void)
50 {
51 int freq, mib[2];
52 size_t size;
53
54 mib[0] = CTL_HW;
55 mib[1] = HW_CPUSPEED;
56
57 size = sizeof(freq);
58
59 if (sysctl(mib, 2, &freq, &size, NULL, 0) < 0) {
60 warn("sysctl 'HW_CPUSPEED':");
61 return NULL;
62 }
63
64 return bprintf("%d", freq);
65 }
66
67 const char *
68 cpu_perc(void)
69 {
70 int mib[2];
71 static int valid;
72 static long int a[CPUSTATES];
73 long int b[CPUSTATES];
74 size_t size;
75
76 mib[0] = CTL_KERN;
77 mib[1] = KERN_CPTIME;
78
79 size = sizeof(a);
80
81 memcpy(b, a, sizeof(b));
82 if (sysctl(mib, 2, &a, &size, NULL, 0) < 0) {
83 warn("sysctl 'KERN_CPTIME':");
84 return NULL;
85 }
86 if (!valid) {
87 valid = 1;
88 return NULL;
89 }
90
91 return bprintf("%d%%", 100 *
92 ((a[CP_USER] + a[CP_NICE] + a[CP_SYS] + a[CP_INTR]) -
93 (b[CP_USER] + b[CP_NICE] + b[CP_SYS] + b[CP_INTR])) /
94 ((a[CP_USER] + a[CP_NICE] + a[CP_SYS] + a[CP_INTR] +
95 a[CP_IDLE]) -
96 (b[CP_USER] + b[CP_NICE] + b[CP_SYS] + b[CP_INTR] +
97 b[CP_IDLE])));
98 }
99 #endif