fork download
  1. #include <iostream>
  2. #include <ctime>
  3. #include <omp.h>
  4.  
  5. const int N = 100000000; // Size of arrays
  6.  
  7. void sequentialAdd(const int* a, const int* b, int* result, int size) {
  8. for (int i = 0; i < size; i++) {
  9. result[i] = a[i] + b[i];
  10. }
  11. }
  12.  
  13. void parallelAdd(const int* a, const int* b, int* result, int size) {
  14. #pragma omp parallel for
  15. for (int i = 0; i < size; i++) {
  16. result[i] = a[i] + b[i];
  17. }
  18. }
  19.  
  20. int main() {
  21. // Allocate dynamic arrays
  22. int* a = new int[N];
  23. int* b = new int[N];
  24. int* result = new int[N];
  25.  
  26. // Initialize arrays with values
  27. for (int i = 0; i < N; ++i) {
  28. a[i] = 1;
  29. b[i] = 2;
  30. }
  31.  
  32. // Sequential addition and timing
  33. clock_t startSeq = clock();
  34. sequentialAdd(a, b, result, N);
  35. clock_t endSeq = clock();
  36. double timeSeq = double(endSeq - startSeq) / CLOCKS_PER_SEC;
  37. std::cout << "Sequential addition time: " << timeSeq << " seconds\n";
  38.  
  39. // Parallel addition and timing
  40. clock_t startPar = clock();
  41. parallelAdd(a, b, result, N);
  42. clock_t endPar = clock();
  43. double timePar = double(endPar - startPar) / CLOCKS_PER_SEC;
  44. std::cout << "Parallel addition time: " << timePar << " seconds\n";
  45.  
  46. // Clean up dynamic arrays
  47. delete[] a;
  48. delete[] b;
  49. delete[] result;
  50.  
  51. return 0;
  52. }
Success #stdin #stdout 0s 5296KB
stdin
Standard input is empty
stdout
Sequential addition time: 0 seconds
Parallel addition time: 0 seconds