Skip to content

Instantly share code, notes, and snippets.

@jsm222
Created February 19, 2017 02:21
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 jsm222/5e20c9c2f496e565637798bd0f897fc0 to your computer and use it in GitHub Desktop.
Save jsm222/5e20c9c2f496e565637798bd0f897fc0 to your computer and use it in GitHub Desktop.
Hacked from top, display overall cpu-usage on FreeBSD..
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <sys/types.h>
#include <sys/sysctl.h>
static int out[CPUSTATES];
static long cp_old[CPUSTATES];
static long cp_diff[CPUSTATES];
char *cpustatenames[] = {
"user", "nice", "system", "interrupt", "idle", NULL
};
long percentages(cnt, out, new, old, diffs)
int cnt;
int *out;
register long *new;
register long *old;
long *diffs;
{
register int i;
register long change;
register long total_change;
register long *dp;
long half_total;
/* initialization */
total_change = 0;
dp = diffs;
/* calculate changes for each state and the overall change */
for (i = 0; i < cnt; i++)
{
if ((change = *new - *old) < 0)
{
/* this only happens when the counter wraps */
change = (int)
((unsigned long)*new-(unsigned long)*old);
}
total_change += (*dp++ = change);
*old++ = *new++;
}
/* avoid divide by zero potential */
if (total_change == 0)
{
total_change = 1;
}
/* calculate percentages based on overall change, rounding up */
half_total = total_change / 2l;
/* Do not divide by 0. Causes Floating point exception */
if(total_change) {
for (i = 0; i < cnt; i++)
{
*out++ = (int)((*diffs++ * 1000 + half_total) / total_change);
}
}
/* return the total in case the caller wants to use it */
return(total_change);
}
void cpu_update()
{
size_t cp_size = sizeof(long) * CPUSTATES*8;
long *cp_times = malloc(cp_size);
if (sysctlbyname("kern.cp_time", cp_times, &cp_size, NULL, 0) < 0) {
perror("sysctlbyname");
free(cp_times);
}
percentages(CPUSTATES, out, cp_times, cp_old, cp_diff);
for(int j=0; j<CPUSTATES;j++) {
printf("%s: %.1f%% - ",cpustatenames[j],((float)out[j])/10.00);
}
printf("\n");
free(cp_times);
}
int
main(int argc, char *argv[])
{
for(int i=0;i<100;i++) {
cpu_update();
sleep(1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment