Advertisement
ulysses4ever

sumtree/OpenMP

Jul 11th, 2024 (edited)
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.03 KB | None | 0 0
  1. /*
  2.  * The sleep command (marked  with **********************) makes all the difference with OpenMP.
  3.  * If sleep is there, we get reasonable speedups with more threads:
  4.  *
  5.  * ❯ gcc -fopenmp ./sumtree.c -o sumtree
  6.  *
  7.  * ❯ OMP_NUM_THREADS=1 ./sumtree
  8.  * time: 1213.934000 ms.
  9.  * res:  16384⏎
  10.  *
  11.  * ❯ OMP_NUM_THREADS=16 ./sumtree
  12.  * time: 113.490000 ms.
  13.  * res:  16384⏎
  14.  *
  15.  * But without the sleep, we get major slowdowns:
  16.  *
  17.  * ❯ OMP_NUM_THREADS=1 ./sumtree
  18.  * time: 2.258000 ms.
  19.  * res:  16384⏎
  20.  *
  21.  * ❯ OMP_NUM_THREADS=16 ./sumtree
  22.  * time: 39.863000 ms.
  23.  * res:  16384⏎
  24.  *
  25.  * This is not true with CilkPlus (see the other file).
  26.  */
  27. #include <stdlib.h>
  28. #include <stdio.h>
  29. #include <omp.h>
  30. #include <unistd.h>
  31. #include <sys/time.h>
  32.  
  33. typedef struct treeS tree;
  34. struct treeS {
  35.     tree* l;
  36.     tree* r;
  37.     int i;
  38. };
  39.  
  40. tree * mktree(int i) {
  41.     if (i<=0) {
  42.         tree* res = (tree*) malloc(sizeof(tree));
  43.         res->l=NULL;res->r=NULL;res->i=1;
  44.         return res;
  45.     }
  46.     else {
  47.         tree* l=mktree(i-1);
  48.         tree* r=mktree(i-1);
  49.         tree* res = (tree*) malloc(sizeof(tree));
  50.         res->l=l;res->r=r;res->i=1;
  51.         return res;
  52.     }
  53. }
  54.  
  55. int sumtree(tree* t) {
  56.     if (t->l == NULL)
  57.         return t->i;
  58.     else {
  59.         int sl;
  60.         #pragma omp task shared(sl)
  61.         sl = sumtree(t->l);
  62.  
  63.         int sr;
  64.         sr = sumtree(t->r);
  65.  
  66.         #pragma omp taskwait
  67.  
  68.         int res = sl + sr;
  69.         //sleep(0.1); /*            **********************           */
  70.         return res;
  71.     }
  72. }
  73.  
  74.  
  75. int main() {
  76.     struct timeval t1, t2;
  77.     double elapsedTime;
  78.     #pragma omp parallel
  79.     {
  80.     #pragma omp single
  81.     {
  82.     tree* t = mktree(14);
  83.  
  84.     gettimeofday(&t1, NULL);
  85.     int res = sumtree(t);
  86.     gettimeofday(&t2, NULL);
  87.  
  88.     elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0;      // sec to ms
  89.     elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0;   // us to ms
  90.     printf("time: %f ms.\n", elapsedTime);
  91.     printf("res:  %d", res);
  92.     }}
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement