/*
 * 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	128			// resolution ca. 8ms

typedef unsigned long clock_t;

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

	if (!done) {
		done = 1;
		Intern_t2con = 0x188;		// count up @xclk/256
	}
	return Intern_t2val;
}

/*
 * 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);

		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
		);
	}
}
