home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / snip9707.zip / BITCNTS.C < prev    next >
C/C++ Source or Header  |  1997-07-05  |  2KB  |  86 lines

  1. /* +++Date last modified: 05-Jul-1997 */
  2.  
  3. /*
  4. **  BITCNTS.C - Test program for bit counting functions
  5. **
  6. **  public domain by Bob Stout & Auke Reitsma
  7. */
  8.  
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <conio.h>
  12. #include <limits.h>
  13. #include <time.h>
  14. #include <float.h>
  15. #include "bitops.h"
  16.  
  17. #define ITERS  1500000L
  18. #define FUNCS  8
  19.  
  20. static int CDECL bit_shifter(long int x);
  21.  
  22. int main(void)
  23. {
  24.       clock_t start, stop;
  25.       double ct, cmin = DBL_MAX, cmax = 0;
  26.       int i, cminix, cmaxix;
  27.       long j, n;
  28.       static int (* CDECL pBitCntFunc[FUNCS])(long) = {
  29.             bit_count,
  30.             bitcount,
  31.             ntbl_bitcnt,
  32.             ntbl_bitcount,
  33.             btbl_bitcnt,
  34.             BW_btbl_bitcount,
  35.             AR_btbl_bitcount,
  36.             bit_shifter
  37.       };
  38.       static char *text[FUNCS] = {
  39.             "Optimized 1 bit/loop counter",
  40.             "Ratko's mystery algorithm",
  41.             "Recursive bit count by nybbles",
  42.             "Non-recursive bit count by nybbles",
  43.             "Recursive bit count by bytes",
  44.             "Non-recursive bit count by bytes (BW)",
  45.             "Non-recursive bit count by bytes (AR)",
  46.             "Shift and count bits"
  47.       };
  48.  
  49.       puts("Bit counter algorithm benchmark\n");
  50.  
  51.       for (i = 0; i < FUNCS; i++)
  52.       {
  53.             start = clock();
  54.  
  55.             for (j = n = 0; j < ITERS; j++)
  56.                   n += pBitCntFunc[i](j);
  57.  
  58.             stop = clock();
  59.             ct = (stop - start) / (double)CLOCKS_PER_SEC;
  60.             if (ct < cmin)
  61.             {
  62.                   cmin = ct;
  63.                   cminix = i;
  64.             }
  65.             if (ct > cmax)
  66.             {
  67.                   cmax = ct;
  68.                   cmaxix = i;
  69.             }
  70.  
  71.             printf("%-38s> Time: %7.3f sec.; Bits: %ld\n", text[i], ct, n);
  72.       }
  73.       printf("\nBest  > %s\n", text[cminix]);
  74.       printf("Worst > %s\n", text[cmaxix]);
  75.       return 0;
  76. }
  77.  
  78. static int CDECL bit_shifter(long int x)
  79. {
  80.       int i, n;
  81.  
  82.       for (i = n = 0; x && (i < (sizeof(long) * CHAR_BIT)); ++i, x >>= 1)
  83.             n += (int)(x & 1L);
  84.       return n;
  85. }
  86.