Skip to content

Instantly share code, notes, and snippets.

@tinkertim
Last active September 28, 2022 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tinkertim/76294004d9df02367405fa312cc26b2f to your computer and use it in GitHub Desktop.
Save tinkertim/76294004d9df02367405fa312cc26b2f to your computer and use it in GitHub Desktop.
Determine the average time a system spends iobound from boot (useful for seeing how stacked & oversold low-cost VMs are)
/* See how much time a system spends in iowait since boot (as a percentage)
* Useful to alert on iobound processes
* Written by Tim Post, March 2008
* Hereby donated to the public domain, or use under the terms of the MIT license.
*/
#include <stdio.h>
#include <time.h>
#include <string.h>
#ifndef USER_HZ
#define USER_HZ 100
#endif
#define BUF_S 64
#define BUF_M 256
#define BUF_L 512
#define BUF_XL 1024
/* Long double is used for precision */
static long double get_average_iowait(void)
{
FILE *fp;
char buff[BUF_XL];
char item[BUF_S];
time_t c_time, u_time, time_val;
long user = 0, nice = 0, system = 0, idle = 0, iowait = 0, btime = 0;
fp = fopen("/proc/stat", "r");
if (! fp) {
fprintf(stderr, "Unable to open /proc/stat\n");
return -1;
}
fgets(buff, BUF_XL, fp);
sscanf(buff, "%s %ld %ld %ld %ld %ld",
item, &user, &nice, &system, &idle, &iowait);
for (;;) {
memset(buff, 0, sizeof(buff));
fgets(buff, BUF_M, fp);
if (feof(fp))
break;
sscanf(buff, "%s %ld", item, &time_val);
if (! strcmp(item, "btime")) {
btime = time_val;
break;
}
}
fclose(fp);
if (btime == 0)
return -1;
c_time = time(NULL);
u_time = c_time - btime;
return (100 * ((long double)(iowait / USER_HZ) / u_time));
}
int main(void)
{
long double io = 0;
io = get_average_iowait();
if (io < 0) {
fprintf(stderr, "Unable to determine boot time from /proc/stat\n");
return 1;
}
printf("This system has spent %-2.5Lf %% of its time in IOWAIT since boot.\n",
io);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment