Advertisement
ulysses4ever

sumtree/CilkPlus

Jul 11th, 2024
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.78 KB | None | 0 0
  1. /*
  2.  * You need GCC 7 to get CilkPlus for free. With the sleep, we get a predictable speedup:
  3.  *
  4.  * $ gcc -fcilkplus ./sumtree_cilk.c -o sumtree
  5.  *
  6.  * $ CILK_NWORKERS=1 ./sumtree
  7.  * time: 1209.847000 ms.
  8.  * res:  16384
  9.  *
  10.  * $ CILK_NWORKERS=16 ./sumtree
  11.  * time: 74.009000 ms.
  12.  * res:  16384
  13.  *
  14.  * Without the sleep we still get a (modest) speedup!
  15.  
  16.  * $ CILK_NWORKERS=1 ./sumtree
  17.  * time: 3.223000 ms.
  18.  * res:  16384
  19.  
  20.  * $ CILK_NWORKERS=16 ./sumtree
  21.  * time: 2.498000 ms.
  22.  * res:  16384
  23.  *
  24.  */
  25. #include <stdlib.h>
  26. #include <stdio.h>
  27. #include <cilk/cilk.h>
  28. #include <unistd.h>
  29. #include <sys/time.h>
  30.  
  31. typedef struct treeS tree;
  32. struct treeS {
  33.     tree* l;
  34.     tree* r;
  35.     int i;
  36. };
  37.  
  38. tree * mktree(int i) {
  39.     if (i<=0) {
  40.         tree* res = (tree*) malloc(sizeof(tree));
  41.         res->l=NULL;res->r=NULL;res->i=1;
  42.         return res;
  43.     }
  44.     else {
  45.         tree* l=mktree(i-1);
  46.         tree* r=mktree(i-1);
  47.         tree* res = (tree*) malloc(sizeof(tree));
  48.         res->l=l;res->r=r;res->i=1;
  49.         return res;
  50.     }
  51. }
  52.  
  53. int sumtree(tree* t) {
  54.     if (t->l == NULL)
  55.         return t->i;
  56.     else {
  57.         int sl;
  58.         sl = cilk_spawn sumtree(t->l);
  59.  
  60.         int sr;
  61.         sr = sumtree(t->r);
  62.  
  63.         cilk_sync;
  64.  
  65.         int res = sl + sr;
  66.         //sleep(0.1); /*            **********************           */
  67.         return res;
  68.     }
  69. }
  70.  
  71.  
  72. int main() {
  73.     struct timeval t1, t2;
  74.     double elapsedTime;
  75.     tree* t = mktree(14);
  76.  
  77.     gettimeofday(&t1, NULL);
  78.     int res = sumtree(t);
  79.     gettimeofday(&t2, NULL);
  80.  
  81.     elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0;      // sec to ms
  82.     elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0;   // us to ms
  83.     printf("time: %f ms.\n", elapsedTime);
  84.     printf("res:  %d", res);
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement