Bit hack: Expanding bits

前端 未结 8 1483
名媛妹妹
名媛妹妹 2021-02-13 21:27

I am trying to convert a uint16_t input to a uint32_t bit mask. One bit in the input toggles two bits in the output bit mask. Here is an example conver

8条回答
  •  误落风尘
    2021-02-13 22:01

    In case you want to get some estimate of relative speeds, some community wiki test code. Adjust as needed.

    void f_cmp(uint32_t (*f1)(uint16_t x), uint32_t (*f2)(uint16_t x)) {
      uint16_t x = 0;
      do {
        uint32_t y1 = (*f1)(x);
        uint32_t y2 = (*f2)(x);
        if (y1 != y2) {
          printf("%4x %8lX %8lX\n", x, (unsigned long) y1, (unsigned long) y2);
        }
      } while (x++ != 0xFFFF);
    }
    
    void f_time(uint32_t (*f1)(uint16_t x)) {
      f_cmp(expand_bits, f1);
      clock_t t1 = clock();
      volatile uint32_t y1 = 0;
      unsigned n = 1000;
      for (unsigned i = 0; i < n; i++) {
        uint16_t x = 0;
        do {
          y1 += (*f1)(x);
        } while (x++ != 0xFFFF);
      }
      clock_t t2 = clock();
      printf("%6llu %6llu: %.6f %lX\n", (unsigned long long) t1,
              (unsigned long long) t2, 1.0 * (t2 - t1) / CLOCKS_PER_SEC / n,
              (unsigned long) y1);
      fflush(stdout);
    }
    
    int main(void) {
      f_time(expand_bits);
      f_time(expandBits);
      f_time(remask);
      f_time(javey);
      f_time(thndrwrks_expand);
      // now in the other order
      f_time(thndrwrks_expand);
      f_time(javey);
      f_time(remask);
      f_time(expandBits);
      f_time(expand_bits);
      return 0;
    }
    

    Results

         0    280: 0.000280 FE0C0000 // fast
       280    702: 0.000422 FE0C0000
       702   1872: 0.001170 FE0C0000
      1872   3026: 0.001154 FE0C0000
      3026   4399: 0.001373 FE0C0000 // slow
    
      4399   5740: 0.001341 FE0C0000
      5740   6879: 0.001139 FE0C0000
      6879   8034: 0.001155 FE0C0000
      8034   8470: 0.000436 FE0C0000
      8486   8751: 0.000265 FE0C0000
    

提交回复
热议问题