#include #include #include #include using namespace std; /* You can see how this is used down in main * It's a function that takes a function and a parameter * It runs the given function on the given parameter * The function returns something, which this function also returns * The first two types can be determined by usage (what parameters are given) * The return type has to be given as a template class argument (see main) * I'll talk about this a little on Monday after giving out the test answers */ template T time_function(U runthis, V parameter){ auto start = chrono::steady_clock::now(); T retval = runthis(parameter); /* See if you can figure out what this line is saying! */ double time_taken = chrono::duration_cast>>(chrono::steady_clock::now() - start).count(); cout << "Time taken: " << time_taken << " milliseconds" << endl; return retval; } /* Notice that calculating fib(x - 1) actually also calculates fib(x - 2), and we need to * use the result instead of losing it. * There are basically three ways to solve this: * 1. Convert to an iterative function * 2. Multiple returns (use a struct) * 3. Save a list of previously-computed values */ int fib(int x){ if(x == 0) return 0; if(x == 1) return 1; return fib(x - 1) + fib(x - 2); } /* Just a helper for the next function. Library round function rounds to the closest integer. */ double round_flexible(double n, double precision){ return round(n / precision) * precision; } /* Returns true if the sin of pi is in the given list, to a precision of 1/10000 */ bool is_sine_of_pi_in_list(vector nums){ bool found = false; for(double n : nums) if(n == round_flexible(sin(3.141592653), 0.0001)) found = true; return found; } /* Optimize both functions, so they still do the same thing but faster. * Standard for success: Both functions <1 millisecond * I *think* this lab is is crazy-overclocked-gaming-computer safe, but if your computer is really * fast and you know it, don't give up at 0.99 milliseconds. */ int main(){ cout << time_function(fib, 35) << endl; vector values; srandom(1); // Consistent seeding values.reserve(5000000); for(int i = 0; i < 5000000; i++) values.push_back((double)(random() % 10000) / 10000.0); cout << time_function(is_sine_of_pi_in_list, values) << endl; return 0; }