int main(int argc, char** argv) { int array[SIZE]; initialize(array, SIZE); assert( sequentialSum(array, SIZE) == parallelSum(array, SIZE) ); printf("Sequential and parallel functions produced the same result\n"); return 0; }
int parallelSum(RAIter begin, RAIter end) { // If length is less than 1000, accumulate all the values in range [begin, end) auto len = end - begin; if (len < 1000) return std::accumulate(begin, end, 0); // Divide and Conquer in parallel RAIter mid = begin + len / 2; auto handle = std::async(std::launch::async, parallelSum<RAIter>, mid, end); int sum = parallelSum(begin, mid); return sum + handle.get(); }
int main() { // Get current time using High resolution clock (C++11) // Count a duration with the time span between the epoch and tthe time_point (C++11) auto seed = std::chrono::high_resolution_clock::now().time_since_epoch().count(); // A random number generator based on Mersenne Twister algorithm (C++11) std::mt19937 mtRand(seed); // Create a vector with 10000 elements std::vector<int> v(10000); // Assign a random number (1 ~ 100) for (auto& value : v) value = mtRand() % 100 + 1; // Print result std::cout << "The sum is " << parallelSum(v.begin(), v.end()) << std::endl; return 0; }