/* Lecture code 16.1
 *
 * Time trial pitting a regular C++ function against a C++ functor.
 * (Hint: the functor wins!)
 */

#include <iostream>
#include <vector>
#include <ctime>
#include <algorithm>
using namespace std;

const int NUM_ELEMS = 1000000;
const int NUM_TESTS = 100;

bool CompareBackwards(int one, int two)
{
	return two < one;
}

void RunFunctionTest(const vector<int>& source)
{
	vector<int> myContainer = source;
	
	clock_t start = clock();

	for(int h = 0; h < NUM_TESTS; h++)
	{
		sort(myContainer.begin(), myContainer.end(), CompareBackwards);
	}

	start = clock() - start;

	cout << "Regular function finished in ";
	cout << ((double)(start) / CLOCKS_PER_SEC);
	cout << " seconds." << endl;
}

struct CompareBackwardsFunctor
{
	bool operator() (int one, int two) const
	{
		return two < one;
	}
};

void RunFunctorTest(const vector<int>& source)
{
	vector<int> myContainer = source;

	clock_t start = clock();

	for(int h = 0; h < NUM_TESTS; h++)
	{
		sort(myContainer.begin(), myContainer.end(), CompareBackwardsFunctor());
	}

	start = clock() - start;

	cout << "Custom functor finished in ";
	cout << ((double)(start) / CLOCKS_PER_SEC);
	cout << " seconds." << endl;
}

int main()
{
	vector<int> sourceVector(NUM_ELEMS);
	generate(sourceVector.begin(), sourceVector.end(), rand);

	RunFunctionTest(sourceVector);
	RunFunctorTest(sourceVector);

	return 0;
}