Advertisement
Guest User

cycle_between_values

a guest
Jul 1st, 2012
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.31 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<time.h>
  3.  
  4.  
  5.  
  6. #define     VAL_ONE             10
  7. #define     VAL_TWO             5
  8. #define     TOTAL_ITERATIONS    1000000
  9.  
  10. // Functional pointer
  11. void (*with_test_pointer)(int *) = NULL;
  12.  
  13. void with_xor(int *value)
  14. {
  15.     *value ^= VAL_ONE ^ VAL_TWO;
  16. }
  17.  
  18.  
  19. void with_conditional(int *value)
  20. {
  21.     *value = (*value == VAL_ONE)? VAL_TWO : VAL_ONE;
  22. }
  23.  
  24. void with_if(int *value)
  25. {
  26.     if(VAL_ONE == *value)
  27.     {  
  28.         *value = VAL_TWO;
  29.     }
  30.     else
  31.     {
  32.         *value = VAL_ONE;
  33.     }
  34.  
  35.  
  36. }
  37.  
  38.  
  39.  
  40. void run_test(void (*with_test_pointer)(int*), double *time_spent)
  41. {
  42.  
  43.     int i;
  44.     clock_t start, end;
  45.     int a = VAL_ONE;
  46.  
  47.     start = clock();
  48.     for(i = 0; i < TOTAL_ITERATIONS; i++)
  49.     {
  50.         (*with_test_pointer)(&a);
  51.     }
  52.     end = clock();
  53.     *time_spent = ((double) (end - start))/ CLOCKS_PER_SEC;
  54.  
  55. }
  56.  
  57.  
  58.  
  59. int main()
  60. {
  61.  
  62.     int i;
  63.     double diff;
  64.     double diff_xor = 0;
  65.     double diff_if = 0;
  66.     double diff_conditional = 0;
  67.  
  68.  
  69.    
  70.     for(i = 0; i < 10; i++)
  71.     {
  72.  
  73.         run_test(&with_xor, &diff);
  74.  
  75.         diff_xor += diff;
  76.  
  77.         run_test(&with_if, &diff);
  78.  
  79.         diff_if += diff;
  80.  
  81.         run_test(&with_conditional, &diff);
  82.  
  83.         diff_conditional += diff;
  84.  
  85.  
  86.     }
  87.  
  88.     printf("xor   %f\t\t\t\n", diff_xor);
  89.  
  90.     printf("conditional   %f\t\t\t\n", diff_conditional);
  91.  
  92.     printf("if   %f\t\t\t\n", diff_if);
  93.  
  94.  
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement