Xinqi Bao's Git

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