aboutsummaryrefslogtreecommitdiff
path: root/cpu.c
blob: a1068c2bfe423b7d1c66f88428e4aedbe8b396c3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <stdio.h>
#include "block.h"
#define ICON_CPU "  "
#define FG "#222222"
#define BG0 "#acae3299"
#define BG1 "#ea544399"
FILE *proc_stat;
int cpu_delay = 6, cpu_stat[8];
char cpu_str[12];
int total, idle;
double cpu_usage_p;
void cpu(void) {
	if (cpu_delay++ < 6) goto show_stat;
	else cpu_delay = 0;
	int prev_idle, prev_total;
	char buf[64];
	prev_idle = idle;
	prev_total = total;
	if (!proc_stat) proc_stat = fopen("/proc/stat","r");
	if (proc_stat) {
		int c, i = 0, j = 0;
		fseek(proc_stat,5,0);
		fgets(buf,64,proc_stat);
		while (i < 8) cpu_stat[i++] = 0;
		for (i = 0; i < 8; i++)
			while ((c = buf[j++]) != ' ')
				cpu_stat[i] = 10 * cpu_stat[i] + (c - '0');
		total = cpu_stat[0]+cpu_stat[1]+cpu_stat[2];
		idle = cpu_stat[3]+cpu_stat[4];
		total += cpu_stat[5]+cpu_stat[6]+cpu_stat[7];
	}
	cpu_usage_p = total - prev_total;
	cpu_usage_p *= 100;
	cpu_usage_p /= ((float)idle + total) - (prev_idle + prev_total);
	snprintf(cpu_str,12,ICON_CPU"%02.02f%%",cpu_usage_p);
show_stat:
	if (cpu_usage_p < 60) block(cpu_str,FG,BG0,BG0);
	else block(cpu_str,FG,BG1,BG1);
}