Erm...
[apc.git] / idlestat.c
blob474756b87f8017488140ca4326c9c4822f082813
1 #define _GNU_SOURCE
2 #include <err.h>
3 #include <time.h>
4 #include <stdio.h>
5 #include <fcntl.h>
6 #include <alloca.h>
7 #include <unistd.h>
8 #include <stdlib.h>
9 #include <sys/time.h>
10 #include <sys/sysinfo.h>
12 static double now (void)
14 struct timeval tv;
16 if (gettimeofday (&tv, NULL))
17 err (1, "gettimeofday");
18 return tv.tv_sec + tv.tv_usec * 1e-6;
21 static void idlenow (int fd, int nprocs, double *p)
23 struct timeval tv;
24 size_t n = nprocs * sizeof (tv);
25 ssize_t m;
26 struct timeval *buf;
27 int i;
29 buf = alloca (n);
30 if (!buf) errx (1, "alloca failed");
32 m = read (fd, buf, n);
33 if (n - m) err (1, "read [n=%zu, m=%zi]", n, m);
35 for (i = 0; i < nprocs; ++i)
36 p[i] = buf[i].tv_sec + buf[i].tv_usec * 1e-6;
39 int main (int argc, char **argv)
41 int fd;
42 int nprocs;
43 double *idle;
44 double *curr, *prev;
46 (void) argc;
47 (void) argv;
49 nprocs = get_nprocs ();
50 if (nprocs <= 0) errx (1, "get_nprocs returned %d", nprocs);
52 idle = malloc (2 * nprocs * sizeof (idle[0]));
53 if (!idle) errx (1, "malloc %zu failed", 2 * nprocs * sizeof (idle[0]));
55 fd = open ("/dev/itc", O_RDONLY);
56 if (fd < 0) err (1, "open /dev/itc");
58 idlenow (fd, nprocs, idle);
60 curr = &idle[nprocs];
61 prev = idle;
62 setbuf (stdout, NULL);
64 for (;;) {
65 int i;
66 double s, e, d, *t, a = 0.0, ai = 0.0;
68 idlenow (fd, nprocs, prev);
69 s = now ();
70 sleep (1);
71 idlenow (fd, nprocs, curr);
72 e = now ();
73 d = e - s;
75 for (i = 0; i < nprocs; ++i) {
76 double di = curr[i] - prev[i];
78 /* printf ("\rcpu%d - %.2f", i, 100.0 * (1.0 - di / d)); */
79 /* printf ("cpu%d - %6.2f\n", i, 100.0 * (1.0 - di / d)); */
80 a += d;
81 ai += di;
82 printf ("%6.2f", 100.0 * (1.0 - di / d));
83 if (i < nprocs) fputc (' ', stdout);
85 if (i > 0) {
86 printf ("%6.2f\n", 100.0 * (1.0 - ai / a));
88 else {
89 fputc ('\n', stdout);
92 t = curr;
93 curr = prev;
94 prev = t;