/* Latency CPU test; core idea designed by Luke Mcpherson
 * Ian Wienand <ianw@gelato.unsw.edu.au>
 * (C) 2005, 2006
 * See README for important information
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <signal.h>

#include "cpuusage_lukem.h"

/* stores timer information */
volatile struct timer_buffer_t timer_buffer;

/* when we flip this, we stop calculating */
static int calc = 1;

void *idle_thread(void *arg)
{
	cycle_t x0, x1, delta, total, idle;

	idle = total = 0;
	x0 = get_cycles();

	while (calc) {
		x1 = x0;
		x0 = get_cycles();

		delta = x0 - x1;
		total += delta;

		/* If the delta looks like less than a context switch,
		 * add this to idle time; otherwise add it to busy
		 * time */
		if (delta < PROFILE_CONTEXT_COST)
			idle += delta;

		timer_buffer.idle = idle;
		timer_buffer.total = total;
	}

	return;
}



void
calculate_usage(int sig)
{
	double cpu_used = (1.f -
			   (double)timer_buffer.idle /
			   (double)timer_buffer.total) * 100;

	printf("Average CPU usage was %.1f%\n", cpu_used);

	exit(0);
}


int main(int argc, char *argv[])
{
	/* put ourselves at a low priority */
	nice(20);

	pthread_t ithr;
	/* create the idle thread */
	pthread_create(&ithr, NULL, idle_thread, NULL);

	printf("Starting measuring - Ctrl-C to stop\n");

	signal(SIGINT, calculate_usage);

	pthread_join(ithr, NULL);

	return 0;
}

