#include #include #include #include #include using namespace std; using namespace std::chrono; typedef pair Timings; /** * Calculate the nth fibonacci recursively. * (Generally a very bad idea.) * @param n which fibonacci number to calculate. */ long fibonacci(int n); /** * Calculate the nth fibonacci recursively in a separate thread. * @return the start and end times as a pair. */ Timings fibonacci_thread(int n); const int N1 = 46; const int N2 = 45; int main() { // The first future result. cout << "Starting thread to calculate fibonacci(" << N1 << ")" << endl; auto times1 = async(launch::async, fibonacci_thread, N1); // The second future result. cout << "Starting thread to calculate fibonacci(" << N2 << ")" << endl; auto times2 = async(launch::async, fibonacci_thread, N2); // Wait for the results from each thread. Timings result1 = times1.get(); Timings result2 = times2.get(); // When the first thread started. auto first_start = (result1.first < result2.first) ? result1.first : result2.first; // When the last thread ended. auto last_end = (result1.second > result2.second) ? result1.second : result2.second; double elapsed = duration_cast(last_end - first_start).count(); cout << endl << "Total elapsed time = " << elapsed/1000 << " seconds" << endl; } Timings fibonacci_thread(int n) { Timings result; auto start = steady_clock::now(); long value = fibonacci(n); auto end = steady_clock::now(); double elapsed = duration_cast(end - start).count(); cout << endl << "fibonacci(" << n << ") = " << value << endl; cout << "Calculation time = " << elapsed/1000 << " seconds" << endl; result.first = start; result.second = end; return result; } long fibonacci(int n) { if (n <= 1) return n; else return fibonacci(n-2) + fibonacci(n-1); }