• Source
    1. #include <stdio.h>
    2. #include <time.h>
    3. #define R2(n) n, n + 2*64, n + 1*64, n + 3*64
    4. #define R4(n) R2(n), R2(n + 2*16), R2(n + 1*16), R2(n + 3*16)
    5. #define R6(n) R4(n), R4(n + 2*4 ), R4(n + 1*4 ), R4(n + 3*4 )
    6.  
    7. static const unsigned char BitReverseTable256[256] =
    8. {
    9. R6(0), R6(2), R6(1), R6(3)
    10. };
    11.  
    12. inline unsigned char ReverseBitsLookupTable(unsigned char v)
    13. {
    14. return BitReverseTable256[v];
    15. }
    16.  
    17. inline unsigned char ReverseBitsSimpleAndElegant(unsigned char ucByte)
    18. {
    19. return (0x10 & ucByte) >> 1 | (0x08 & ucByte) << 1 |
    20. (0x20 & ucByte) >> 3 | (0x04 & ucByte) << 3 |
    21. (0x40 & ucByte) >> 5 | (0x02 & ucByte) << 5 |
    22. (0x80 & ucByte) >> 7 | (0x01 & ucByte) << 7;
    23. }
    24.  
    25. inline unsigned char ReverseBits7ops32bit(unsigned char v)
    26. {
    27. return ((v * 0x0802LU & 0x22110LU) |
    28. (v * 0x8020LU & 0x88440LU)) * 0x10101LU >> 16;
    29. }
    30.  
    31. typedef unsigned char (*ReverseBitsFunc)(unsigned char);
    32.  
    33. unsigned int TestFunc(const char * desc, ReverseBitsFunc func)
    34. {
    35. const unsigned int uiFunctionCallCount = 200000000;
    36.  
    37. unsigned int res = 0;
    38. clock_t begin = clock();
    39. for(int i = 0; i < uiFunctionCallCount; ++i)
    40. {
    41. res += func((unsigned char)i);
    42. }
    43.  
    44. clock_t end = clock();
    45.  
    46. printf("%u calls of %s takes %lf seconds.\n", uiFunctionCallCount, desc,
    47. (double)(end - begin)/(double)CLOCKS_PER_SEC);
    48.  
    49. return res;
    50. }
    51.  
    52. int main()
    53. {
    54. TestFunc("ReverseBitsSimpleAndElegant", ReverseBitsSimpleAndElegant);
    55. TestFunc("ReverseBitsLookupTable", ReverseBitsLookupTable);
    56. TestFunc("ReverseBits7ops32bit", ReverseBits7ops32bit);
    57.  
    58. return 0;
    59. }