Advertisement
B1KMusic

1+3+5+... benchmark source code

Nov 26th, 2018
281
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.08 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. #ifndef TEST
  4. #    define TEST 1
  5. #endif
  6.  
  7. #define SQUARE(a) \
  8.     ((a) * (a))
  9.  
  10. unsigned long
  11. oddsum_On(unsigned long n)
  12. {
  13.     unsigned long total = 0;
  14.  
  15.     for(unsigned long i = 1; i <= n; i += 2)
  16.         total += i;
  17.  
  18.     return total;
  19. }
  20.  
  21. unsigned long
  22. oddsum_O2n(unsigned long n)
  23. {
  24.     unsigned long total = 0;
  25.  
  26.     for(unsigned long i = 0; i <= n; ++i)
  27.         if(i % 2 == 1)
  28.             total += i;
  29.  
  30.     return total;
  31. }
  32.  
  33. unsigned long
  34. oddsum_O1(unsigned long n)
  35. {
  36.     return SQUARE( (n + 1) / 2 );
  37. }
  38.  
  39. int
  40. main(void)
  41. {
  42. #if TEST == 1
  43.     // verify that the functions work correctly
  44.     printf("%lu\n", oddsum_O1(111));
  45.     printf("%lu\n", oddsum_On(111));
  46.     printf("%lu\n", oddsum_O2n(111));
  47. #elif TEST == 2
  48.     // benchmark O(1) solution
  49.     oddsum_O1(4000000001L);
  50. #elif TEST == 3
  51.     // benchmark O(n) solution
  52.     oddsum_On(4000000001L);
  53. #elif TEST == 4
  54.     // benchmark O(2n) solution
  55.     oddsum_O2n(4000000001L);
  56. #endif
  57.     // example:
  58.     // cc odds.c -DTEST=2 && time ./a.out
  59.     // this benchmarks the O(1) solution
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement