#include #include #include #include #include static unsigned long long gett(void) { struct timeval tv; if (gettimeofday(&tv, NULL)) perror("gettimeofday"), exit(1); return (unsigned long long)tv.tv_sec * 1000000 + tv.tv_usec; } static void rd(unsigned long long *u1, unsigned long long *u2, unsigned long long *u3) { unsigned long long us, ni, sy, id, iow, irq, sirq; FILE *f; if (!(f = fopen("/proc/stat", "r"))) perror("fopen"), exit(1); if (fscanf(f, "cpu %llu %llu %llu %llu %llu %llu %llu", &us, &ni, &sy, &id, &iow, &irq, &sirq) != 7) fprintf(stderr, "bad file format\n"), exit(1); if (fclose(f)) perror("fclose"), exit(1); *u1 = us + ni + sy; *u2 = id + iow; *u3 = irq + sirq; } static unsigned long long u0, u1, u2, u3; static unsigned long long v0, v1, v2, v3; void sig(int __attribute__((unused)) signo) { rd(&v1, &v2, &v3); v0 = gett(); printf("busy: %f%%\n", (v1 - u1) / 56. / 100. / ((v0 - u0) / 1000000.) * 100.); printf("idle: %f%%\n", (v2 - u2) / 56. / 100. / ((v0 - u0) / 1000000.) * 100.); printf("irq: %f%%\n", (v3 - u3) / 56. / 100. / ((v0 - u0) / 1000000.) * 100.); } int main(void) { rd(&u1, &u2, &u3); u0 = gett(); signal(SIGINT, sig); pause(); return 0; }