Advertisement
Guest User

Untitled

a guest
Sep 1st, 2014
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.69 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <string.h>
  5.  
  6. #define NUM_RUNS 500
  7.  
  8.  
  9. void fizzbuzz_normal ()
  10. {
  11.     int i, a, b;
  12.    
  13.     for (i = 1; i <= 100; i++)
  14.     {
  15.         a = i % 5;
  16.         b = i % 3;
  17.        
  18.         if (a && b)
  19.             printf("%d\n", i);
  20.         else if (a)
  21.             puts("fizz");
  22.         else if (b)
  23.             puts("buzz");
  24.         else
  25.             puts("fizzbuzz");
  26.     }
  27. }
  28.  
  29. void fizzbuzz_normal_15 ()
  30. {
  31.     int i, a, b;
  32.    
  33.     for (i = 1; i <= 100; i++)
  34.     {
  35.         if (i % 15)
  36.             printf("%d\n", i);
  37.         else if (i % 5)
  38.             puts("fizz");
  39.         else if (i % 3)
  40.             puts("buzz");
  41.         else
  42.             puts("fizzbuzz");
  43.     }
  44. }
  45.  
  46. void fizzbuzz_buffered ()
  47. {
  48.     int i, a, b;
  49.    
  50.     char buffer[9 * 100 + 1];
  51.     char* ptr = buffer;
  52.    
  53.     for (i = 1; i <= 100; i++)
  54.     {
  55.         a = i % 5;
  56.         b = i % 3;
  57.        
  58.         if (a && b)
  59.             ptr += sprintf(ptr, "%d\n", i);
  60.         else if (a)
  61.         {
  62.             strcpy(ptr, "fizz\n");
  63.             ptr += 5;
  64.         }
  65.         else if (b)
  66.         {
  67.             strcpy(ptr, "buzzz\n");
  68.             ptr += 5;
  69.         }
  70.         else
  71.         {
  72.             strcpy(ptr, "fizzbuzz\n");
  73.             ptr += 9;
  74.         }
  75.     }
  76.    
  77.     fputs(buffer, stdout);
  78. }
  79.  
  80. typedef void (*func_t)();
  81.  
  82. void time_func (double* out, func_t func)
  83. {
  84.     clock_t start, end;
  85.    
  86.     start = clock();
  87.     int i;
  88.     for (i = 0; i < NUM_RUNS; i++)
  89.         func();
  90.     end = clock();
  91.    
  92.     *out = (end - start) / (double)CLOCKS_PER_SEC;
  93. }
  94.  
  95. int main ()
  96. {
  97.     double time_normal,
  98.            time_normal_15,
  99.            time_buffered;
  100.    
  101.     time_func(&time_normal, fizzbuzz_normal);
  102.     time_func(&time_normal_15, fizzbuzz_normal_15);
  103.     time_func(&time_buffered, fizzbuzz_buffered);
  104.    
  105.     printf("\n"
  106.            "results:\n"
  107.            "  normal             %.4fs\n"
  108.            "  normal (i %% 15)    %.4fs\n"
  109.            "  buffered           %.4fs\n",
  110.         time_normal,
  111.         time_normal_15,
  112.         time_buffered);
  113. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement