daily pastebin goal
56%
SHARE
TWEET

Untitled

a guest Mar 18th, 2019 52 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <time.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. typedef struct slist {
  6.     int val;
  7.     struct slist *next;
  8. } slist_t;
  9.  
  10. typedef struct {
  11.     const char *name;
  12.     clock_t build;
  13.     clock_t iterate;
  14.     int result;
  15. } result_t;
  16.  
  17. result_t array(int count)
  18. {
  19.     clock_t start = clock();
  20.  
  21.     int *arr = malloc(count * sizeof(int));
  22.  
  23.     for (int i = 0; i < count; i++)
  24.         arr[i] = 1;
  25.  
  26.     clock_t build = clock();
  27.  
  28.     int sum = 0;
  29.     for (int i = 0; i < count; i++)
  30.         sum += arr[i];
  31.  
  32.     clock_t done = clock();
  33.  
  34.     free(arr);
  35.  
  36.     return (result_t){"array", build - start, done - build, sum};
  37. }
  38.  
  39. result_t slist(int count)
  40. {
  41.     clock_t start = clock();
  42.  
  43.     slist_t *list = NULL;
  44.  
  45.     for (int i = 0; i < count; i++)
  46.     {
  47.         slist_t *new = malloc(sizeof(slist_t));
  48.         new->val = 1;
  49.         new->next = list;
  50.         list = new;
  51.     }
  52.  
  53.     clock_t build = clock();
  54.  
  55.     int sum = 0;
  56.     slist_t *l = list;
  57.     while (l)
  58.     {
  59.         sum += l->val;
  60.         l = l->next;
  61.     }
  62.  
  63.     clock_t done = clock();
  64.  
  65.     l = list;
  66.     while (l)
  67.     {
  68.         slist_t *next = l->next;
  69.         free(l);
  70.         l = next;
  71.     }
  72.  
  73.     return (result_t){"list", build - start, done - build, sum};
  74. }
  75.  
  76. void runTest(int num, int count, result_t (*test)(int))
  77. {
  78.     result_t master = {0, 0, 0, 0};
  79.  
  80.     for (int i = 0; i < num; i++)
  81.     {
  82.         result_t result = test(count);
  83.  
  84.         master.name = result.name;
  85.         master.build += result.build;
  86.         master.iterate += result.iterate;
  87.         master.result += result.result;
  88.     }
  89.  
  90.     printf ("%10s build %2.8lf iterate %2.8lf result %d\n",
  91.             master.name,
  92.             master.build / (double) CLOCKS_PER_SEC,
  93.             master.iterate / (double) CLOCKS_PER_SEC,
  94.             master.result);
  95. }
  96.  
  97. int main()
  98. {
  99.     result_t (*tests[2])(int) = {array, slist};
  100.  
  101.     for (int i = 0; i < 2; i++)
  102.         runTest(10, 100000000, tests[i]);
  103.        
  104.     return 1;
  105.  
  106. };
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top