#include <sys/time.h>
#include <time.h>
#include <iostream>

using namespace std;

static unsigned max_iter = 30;

void recursion_throwing(unsigned iteration, unsigned max)
{
	unsigned stupid;

	if (iteration == max_iter)
		//throw(false); // normally don't throw, see main text
		return;

	for (unsigned i = 0; i < max; ++i)
		stupid++;

	if (stupid)
		recursion_throwing(iteration + 1, max);
}

bool recursion_nonthrowing(unsigned iteration, unsigned max)
{
	unsigned stupid;
	bool returncode = true;

	if (iteration == max_iter)
		return false;

	for (unsigned i = 0; i < max; ++i)
		stupid++;

	if (stupid)
		returncode = recursion_nonthrowing(iteration + 1, max);

	if (returncode)
		return true;

	return false;
}


bool test_throwing(unsigned max)
try 
{
	recursion_throwing(0, max);
	return true;
}
catch (bool b)
{ 
	return b;
}

bool test_nonthrowing(unsigned max)
{
	return recursion_nonthrowing(0, max);
}

double time_test(bool throwing, unsigned max)
{
	struct timeval start;
	struct timeval end;
	bool returncode;

	gettimeofday(&start, 0);

	if (throwing)
		returncode = test_throwing(max);
	else
		returncode = test_nonthrowing(max);

	gettimeofday(&end, 0);

	double diff = end.tv_usec - start.tv_usec;
	diff += (end.tv_sec - start.tv_sec) * 1000000.0;

	return diff;
}

int main(int argc, char **argv)
{
	double t1, t2;
	unsigned max = 100000000;
	t1 = time_test(true, max);
	t2 = time_test(false, max);

	cout << "ratio throwing/nonthrowing: " << t1 << "ms / "
	     << t2 << "ms = " << t1 / t2 << endl;

	max_iter = 0;

	t1 = time_test(true, 0);
	t2 = time_test(false, 0);

	cout << "ratio throwing/nonthrowing: " << t1 << "ms / "
	     << t2 << "ms = " << t1 / t2 << endl;

	return 0;
}

