Write a C++ program that adds the elements of two arrays with a K million elements each.…
- User
Write a C++ program that adds the elements of two arrays with a K million elements each. Here K is a parameter. Profile and get the time to execute this program for K=1,5,10,50,100. Use free() to free the memory at the end of the program.
Assistant
#include <iostream> #include <cstring> #include <algorithm> using namespace std; int main(int argc, char* argv[]) { if (argc < 2) { cout << "Usage: " << argv[0] << " <first array>" << endl; return 1; } int K = atoi(argv[1]); int n1 = atoi(argv[2]); int n2 = atoi(argv[3]); if (K <= 0 || n1 <= 0 || n2 <= 0) { cout << "K must be a positive integer and the two arrays must have at least 2 elements." << endl; return 1; } int* first_array(n1); int* second_array(n2); int* result(n1); for (int i = 0; i < n1; i++) { first_array[i] = atoi(argv[4 + i]); } for (int i = 0; i < n2; i++) { second_array[i] = atoi(argv[5 + i]); } for (int i = 0; i < n1; i++) { result[i] = first_array[i] + second_array[i]; } int time = 0; for (int i = 0; i < K; i++) { for (int j = 0; j < n1; j++) { for (int k = 0; k < n2; k++) { if (result[j] != -1) { time += abs(result[j] - result[k]); } } } cout << "Adding elements took " << time << " seconds." << endl; time = 0; } cout << "Total time to execute program: " << time << endl; free(first_array); free(second_array);
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.