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 "bitcount-conio.h" |
---|
12 | #include <limits.h> |
---|
13 | #include <time.h> |
---|
14 | #include <float.h> |
---|
15 | #include "bitcount-bitops.h" |
---|
16 | |
---|
17 | #define FUNCS 7 |
---|
18 | |
---|
19 | static int CDECL bit_shifter(long int x); |
---|
20 | |
---|
21 | int main_bitcount(int argc, char *argv[]) |
---|
22 | { |
---|
23 | clock_t start, stop; |
---|
24 | double ct, cmin = DBL_MAX, cmax = 0; |
---|
25 | int i, cminix = 0, cmaxix = 0; |
---|
26 | long j, n, seed; |
---|
27 | int iterations; |
---|
28 | static int (* CDECL pBitCntFunc[FUNCS])(long) = { |
---|
29 | bit_count, |
---|
30 | bitcount, |
---|
31 | ntbl_bitcnt, |
---|
32 | ntbl_bitcount, |
---|
33 | /* btbl_bitcnt, DOESNT WORK*/ |
---|
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 | if (argc<2) { |
---|
49 | fprintf(stderr,"Usage: bitcnts <iterations>\n"); |
---|
50 | exit(-1); |
---|
51 | } |
---|
52 | iterations=atoi(argv[1]); |
---|
53 | |
---|
54 | puts("Bit counter algorithm benchmark\n"); |
---|
55 | |
---|
56 | for (i = 0; i < FUNCS; i++) { |
---|
57 | start = clock(); |
---|
58 | |
---|
59 | for (j = n = 0, seed = rand(); j < iterations; j++, seed += 13) |
---|
60 | n += pBitCntFunc[i](seed); |
---|
61 | |
---|
62 | stop = clock(); |
---|
63 | ct = (stop - start) / (double)CLOCKS_PER_SEC; |
---|
64 | if (ct < cmin) { |
---|
65 | cmin = ct; |
---|
66 | cminix = i; |
---|
67 | } |
---|
68 | if (ct > cmax) { |
---|
69 | cmax = ct; |
---|
70 | cmaxix = i; |
---|
71 | } |
---|
72 | |
---|
73 | printf("%-38s> Time: %7.3f sec.; Bits: %ld\n", text[i], ct, n); |
---|
74 | } |
---|
75 | printf("\nBest > %s\n", text[cminix]); |
---|
76 | printf("Worst > %s\n", text[cmaxix]); |
---|
77 | return 0; |
---|
78 | } |
---|
79 | |
---|
80 | static int CDECL bit_shifter(long int x) |
---|
81 | { |
---|
82 | int i, n; |
---|
83 | |
---|
84 | for (i = n = 0; x && (i < (sizeof(long) * CHAR_BIT)); ++i, x >>= 1) |
---|
85 | n += (int)(x & 1L); |
---|
86 | return n; |
---|
87 | } |
---|