/*** CPULOAD. Provide a rough measure of CPU load. / / Typically invoked as: / cpuload load.txt >>load.log / / Arguments: / load.txt load & store "previous" load values in this file. / load.log append load reports to end of this file. / config full pathname of SWEB configuration file. / secure security code for this subserver. / / Purpose: / Compute approximate measure of CPU loading within a time interval. / / How it works: / Reads the current # secs up and # secs in idle process from / /proc/uptime. Reads previous #secs up and #secs idle from / load.txt. Computes load as / 1 - (current idle - previous idle) / ------------------------------ / (current total - previous total) / / and writes one line to stdout with current date & time / and 3 decimal places of load average. / / Then writes current idle, total times to load.txt for / the next time cpuload is run. Note that date/time and / load average are tab separated, to make this easy to load / into a spreadsheet (and presumably graph). / / Typically cpuload would be run from cron at regular intervals / to compute & save load averages over fixed time intervals. / / Home: cpuload.c / */ /*** Copyright (C) 2002 Charles Roth. All rights reserved. */ /*** This program is published as "open source", in the form of the / MIT artistic license. It may be used by anyone for any purpose, / as long as this notice is retained. The author is not liable for / any damages resulting from the use or misuse of this code. / / Charles Roth, 4/12/2002, www.thedance.net. / */ #include #include main (int argc, char *argv[]) { FILE *fp; int prev_total, prev_idle, this_total, this_idle; int diff_total, diff_idle; int j1, j2; int now; int percent; float usage; struct tm *p; /*** Get the "previous" total & idle times. */ if ( (fp = fopen (argv[1], "r")) != NULL) { fscanf (fp, "%d %d", &prev_total, &prev_idle); fclose (fp); } else prev_total = prev_idle = 0; /*** Get the current total & idle times from /proc/uptime. */ if ( (fp = fopen ("/proc/uptime", "r")) == NULL) exit(1); fscanf (fp, "%d.%d %d.%d", &this_total, &j1, &this_idle, &j2); fclose (fp); /*** Compute load average, being careful about boundary conditions. */ diff_idle = this_idle - prev_idle; if (diff_idle < 0) diff_idle = 0; diff_total = this_total - prev_total; if (diff_total <= 0) diff_total = 1; usage = ((float) diff_idle) / ((float) diff_total); percent = 1000 * (1. - usage); if (percent > 999) percent = 999; /*** Write report line with current date & time. */ now = time(NULL); p = localtime (&now); printf ("%4d-%02d-%02d %02d:%02d .%03d\n", p->tm_year + 1901, p->tm_mon+1, p->tm_mday, p->tm_hour, p->tm_min, percent); /*** Save current total & idle as "previous" for next run! */ if ( (fp = fopen (argv[1], "w")) != NULL) { fprintf (fp, "%d %d\n", this_total, this_idle); fclose (fp); } }