#include <stdio.h>
#include <unistd.h>

int get_cpu_info( unsigned long *user, unsigned long *nice, unsigned long *sys, unsigned long *idle)
{
	int find = 0;
	char buf[1024];
	FILE *stat;

	stat = fopen("/proc/stat", "r");

	if(!stat) {
		fprintf(stderr, "Can not open /proc/stat\n");
		exit(-1);
	}

	while( !feof(stat) ) {
		fgets(buf, 1024, stat);
		if( buf[0] == 'c' && buf[1] == 'p' && buf[2] == 'u' ) {
			find = 1;
			break;
		}
	}

	fclose(stat);

	/* not find cpu infomation */
	if(!find) {
		fprintf(stderr, "Can not get cpu info from /proc/stat\n");
		exit(-1);
	}

	/* read info from buf */
	/* buf + 3 是為了略過開頭的 "cpu" */
	sscanf(buf + 3, "%lu %lu %lu %lu", user, nice, sys, idle);

	return 0;
}

double get_cpu_load( unsigned long delay )
{
	double load;
	unsigned long old_user, old_nice, old_sys, old_idle;
	unsigned long new_user, new_nice, new_sys, new_idle;
	unsigned long user, nice, sys, idle, total;

	/* 前後取兩次資料，中間間隔 delay microseconds */
	get_cpu_info( &old_user, &old_nice, &old_sys, &old_idle );
	usleep( delay );
	get_cpu_info( &new_user, &new_nice, &new_sys, &new_idle );

	user = new_user - old_user;
	nice = new_nice - old_nice;
	sys = new_sys - old_sys;
	idle = new_idle - old_idle;

	load = 1.0 - 1.0 * idle / (user + nice + sys + idle);
	return load;
}

main()
{
	printf("%.0f%%\n", 100 * get_cpu_load(1000000));
}

