/*
 * Copyright(C) Paul und Scherer (mct.de/mct.net)
 *
 * This example demonstrates how to...
 *
 *  ... measure program execution time.
 */

#include <stdio.h>
#include <target.h>

#define CLOCKS_PER_SEC	100			// resolution 10ms

typedef unsigned long clock_t;

/*
 * Initialize Timer1 to count clocks (only
 * the first call). 1 clock equals 1s/100.
 *
 * Return clock count.
 */
static clock_t
clock(void)
{
	static int done;			// skip if already done

	if (!done) {
		done = 1;
		Intern_t1tcr = 2;		// stop, reset
		Intern_t1pr  = _PCLK/100-1;	// inc every 10ms
		Intern_t1tcr = 1;		// go...
	}
	return Intern_t1tc;
}

/*
 * You are prompted for a count, then the program
 * measures the time it takes to execute an empty
 * loop count times.
 */
int
main(void)
{
	while (1) {
		clock_t start, stop;		// start/stop
		char line[20];			// input buffer
		unsigned long count;		// loop count

		fputs("Enter loop count: ", stdout);
		fgets(line, sizeof(line), stdin);
		if (sscanf(line, "%lu", &count) != 1) continue;
		fputs("Looping... ", stdout), fflush(stdout);

		start = clock();		// clocks at start
		while (count--) ;		// loop...
		stop = clock();			// clocks at stop

		printf("%lums (+/-%dms)\n\n",
			(stop-start)*1000 /CLOCKS_PER_SEC,
		   (CLOCKS_PER_SEC/2+1000)/CLOCKS_PER_SEC
		);
	}
}
