Skip to content

Instantly share code, notes, and snippets.

@pixelcmtd
Created May 1, 2020 23:37
Show Gist options
  • Select an option

  • Save pixelcmtd/a2ea87bc69190a88569e6bfd7ffc129f to your computer and use it in GitHub Desktop.

Select an option

Save pixelcmtd/a2ea87bc69190a88569e6bfd7ffc129f to your computer and use it in GitHub Desktop.
//This file is licensed under the BSD 3-clause license and based on i3/i3status.
#include <sys/sysinfo.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
static int prev_idle = 0, prev_total = 0;
int print_cpu_usage() {
int curr_idle = 0, curr_total = 0;
FILE *f = fopen("/proc/stat", "r");
if (!f) goto error;
char line[4096];
fgets(line, sizeof(line), f);
for(int i = 0; i < get_nprocs(); i++) {
fgets(line, sizeof(line), f);
int id, user, nice, system, idle;
sscanf(line, "cpu%d %d %d %d %d", &id, &user, &nice, &system, &idle);
curr_idle += idle;
curr_total += user + nice + system + idle;
}
fclose(f);
int diff_idle = curr_idle - prev_idle;
int diff_total = curr_total - prev_total;
double diff_usage = (diff_total ? (1000 * ((double)diff_total - (double)diff_idle) / (double)diff_total + 5) / 10 : 0);
prev_idle = curr_idle;
prev_total = curr_total;
char buf[16];
int len = sprintf(buf, "%f\n", diff_usage);
f = fopen("/tmp/cpu.txt", "w");
if(!f) goto error;
fwrite(buf, 1, len, f);
fclose(f);
return 0;
error:
puts("Encountered an error:");
perror(NULL);
return 1;
}
int main() {
while(!print_cpu_usage()) sleep(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment