secondary cache feature in vm.
[minix.git] / lib / libsys / getidle.c
blob90893fbfea19e045863cd9dde96480830ece9e21
1 /* getidle.c - by David van Moolenbroek <dcvmoole@cs.vu.nl> */
3 /* Usage:
5 * double idleperc;
6 * getidle();
7 * ...
8 * idleperc = getidle();
9 * printf("CPU usage: %lg%%\n", 100.0 - idleperc);
11 * This routine goes through PM to get the idle time, rather than making the
12 * sys_getinfo() call to the kernel directly. This means that it can be used
13 * by non-system processes as well, but it will incur some extra overhead in
14 * the system case. The overhead does not end up being measured, because the
15 * system is clearly not idle while the system calls are being made. In any
16 * case, for this reason, only one getidle() run is allowed at a time.
18 * Note that the kernel has to be compiled with CONFIG_IDLE_TSC support.
21 #define _MINIX 1
22 #define _SYSTEM 1
23 #include <minix/sysinfo.h>
24 #include <minix/u64.h>
25 #include <minix/sysutil.h>
27 static u64_t start, idle;
28 static int running = 0;
30 static double make_double(u64_t d)
32 /* Convert a 64-bit fixed point value into a double.
33 * This whole thing should be replaced by something better eventually.
35 double value;
36 size_t i;
38 value = (double) ex64hi(d);
39 for (i = 0; i < sizeof(unsigned long); i += 2)
40 value *= 65536.0;
42 value += (double) ex64lo(d);
44 return value;
47 double getidle(void)
49 u64_t stop, idle2;
50 u64_t idelta, tdelta;
51 double ifp, tfp, rfp;
52 int r;
54 if (!running) {
55 r = getsysinfo_up(PM_PROC_NR, SIU_IDLETSC, sizeof(idle), &idle);
56 if (r != sizeof(idle))
57 return -1.0;
59 running = 1;
61 read_tsc_64(&start);
63 return 0.0;
65 else {
66 read_tsc_64(&stop);
68 running = 0;
70 r = getsysinfo_up(PM_PROC_NR, SIU_IDLETSC, sizeof(idle2), &idle2);
71 if (r != sizeof(idle2))
72 return -1.0;
74 idelta = sub64(idle2, idle);
75 tdelta = sub64(stop, start);
77 if (cmp64(idelta, tdelta) >= 0)
78 return 100.0;
80 ifp = make_double(idelta);
81 tfp = make_double(tdelta);
83 rfp = ifp / tfp * 100.0;
85 if (rfp < 0.0) rfp = 0.0;
86 else if (rfp > 100.0) rfp = 100.0;
88 return rfp;
91 running = !running;