devdbi

sillysort_parallel

Aug 27th, 2020
1,481
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.48 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <omp.h>
  4.  
  5. /**
  6.  * Tempo sequencial: 2.347s
  7.  * Tempo paralelo sem politica: 1.230s    
  8.  * Tempo paralelo com politica: 1.168s
  9.  */
  10. int main()
  11. {
  12.    int i, j, n = 30000;
  13.  
  14.    // Allocate input, output and position arrays
  15.    int *in = (int*) calloc(n, sizeof(int));
  16.    int *pos = (int*) calloc(n, sizeof(int));  
  17.    int *out = (int*) calloc(n, sizeof(int));  
  18.  
  19.    #pragma omp parallel num_threads(2)
  20.    {
  21.  
  22.         // Initialize input array in the reverse order
  23.         #pragma omp for private(i)
  24.         for(i=0; i < n; i++)
  25.                 in[i] = n-i;  
  26.        
  27.         // Print input array
  28.         //   for(i=0; i < n; i++)
  29.         //      printf("%d ",in[i]);
  30.        
  31.         // Silly sort (you have to make this code parallel)
  32.         #pragma omp for private (i) collapse(2) reduction(+:pos[:n]) schedule(dynamic, 1250)
  33.         for(i=0; i < n; i++)
  34.             for(j=0; j < n; j++)
  35.                 if(in[i] > in[j])
  36.                     pos[i]++;  
  37.  
  38.         // Move elements to final position
  39.         #pragma omp for private(i)
  40.             for(i=0; i < n; i++)
  41.                 out[pos[i]] = in[i];
  42.    }
  43.  
  44.     // print output array
  45.     //   for(i=0; i < n; i++)
  46.     //      printf("%d ",out[i]);
  47.  
  48.     // Check if answer is correct
  49.     for(i=0; i < n; i++)
  50.         if(i+1 != out[i])
  51.         {
  52.             printf("test failed\n");
  53.             exit(0);
  54.         }
  55.  
  56.     printf("test passed\n");
  57. }  
  58.  
Advertisement
Add Comment
Please, Sign In to add comment