fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <omp.h>
  4.  
  5. #define SIZE 1000000
  6.  
  7. int main() {
  8. int *arr = (int*)malloc(SIZE * sizeof(int));
  9. int sum_parallel_for = 0;
  10. int sum_sections = 0;
  11.  
  12. // Initialize array with random values
  13. for (int i = 0; i < SIZE; ++i) {
  14. arr[i] = rand() % 100;
  15. }
  16.  
  17. // Work sharing with parallel for
  18. #pragma omp parallel for reduction(+:sum_parallel_for)
  19. for (int i = 0; i < SIZE; ++i) {
  20. sum_parallel_for += arr[i];
  21. }
  22.  
  23. // Work sharing with sections
  24. #pragma omp parallel sections
  25. {
  26. #pragma omp section
  27. {
  28. for (int i = 0; i < SIZE / 2; ++i) {
  29. sum_sections += arr[i];
  30. }
  31. }
  32. #pragma omp section
  33. {
  34. for (int i = SIZE / 2; i < SIZE; ++i) {
  35. sum_sections += arr[i];
  36. }
  37. }
  38. }
  39.  
  40. printf("Sum using parallel for: %d\n", sum_parallel_for);
  41. printf("Sum using sections: %d\n", sum_sections);
  42.  
  43. free(arr);
  44.  
  45. return 0;
  46. }
Success #stdin #stdout 0.03s 5284KB
stdin
Standard input is empty
stdout
Sum using parallel for: 49498583
Sum using sections: 49498583