cpu.c (1535B)
1 #include <stdio.h> 2 #include <string.h> 3 4 #include "../util.h" 5 #include "cpu.h" 6 7 #define ICON " " 8 9 /* with /proc/stat one could watch every single core */ 10 #define STATFILE "/proc/uptime" 11 #define MAX_CHARS_PER_LINE 40 12 #define CPUINFOFILE "/proc/cpuinfo" 13 /* IMPORTANT: idle is the sum of the cores, but uptime real time */ 14 15 int get_core_number() { 16 static int corenum = 0; 17 18 // core number only has to be read once 19 if (!corenum) { 20 FILE *cpufile; 21 char tmpstring[MAX_CHARS_PER_LINE]; 22 23 cpufile = fopen(CPUINFOFILE, "r"); 24 while (fgets(tmpstring, MAX_CHARS_PER_LINE, cpufile)) { 25 if (!strncmp(tmpstring, "processor", 9)) corenum++; 26 } 27 fclose(cpufile); 28 } 29 30 return corenum; 31 } 32 33 size_t cpuu(char *str, int sigval) 34 { 35 float uptime; 36 float idle; 37 38 static float last_uptime = 0; 39 static float last_idle = 0; 40 41 char tmpstring[MAX_CHARS_PER_LINE]; 42 43 float usage; /* needed as temporary var */ 44 45 FILE *statfile; 46 47 48 statfile = fopen(STATFILE, "r"); 49 fgets(tmpstring, MAX_CHARS_PER_LINE, statfile); 50 fclose(statfile); 51 52 sscanf(tmpstring, "%f %f", &uptime, &idle); 53 54 usage = 100 * (1 - ((idle - last_idle) / get_core_number() / (uptime - last_uptime))); 55 56 last_uptime = uptime; 57 last_idle = idle; 58 59 /* sometimes usage is negative, which is really weird... */ 60 if (usage < 0) usage = 0; 61 62 return SPRINTF(str, ICON "%03d%%", (int) usage); 63 } 64 65 void cpuc(int button) 66 { 67 TERMCMD("htop", "-s", "PERCENT_CPU"); 68 }