Tuesday, May 29, 2018

Which is Faster, Raising Power or Bit Shifts?

Running graphics bit comparisons can eat up a lot of clock cycles. The way one comes up with the comparison value can make a big difference.

Recently I wanted to remap the bits inside a series of files I had saved from raw video frame dumps. One problem is there are thirty two comparisons being run for each pixel, so this can be really slow.

The examples below show my comparison and remapping routine being debugged with one difference. In the first case the comparisons are generated by raising a power, and in the second the number is generated by bit-shifting one.

masks() contains a set of thirty two integers that would be OR-ed to the output integer based on single-bit triggers in the original color

fileName is the name of my original dump file (a flat file containing nothing but color integers)

Raising Two to a Power to Use for Comparison
Below is my code for running the comparisons, and writing a new integer set, using 2 ^ lt3, to generate the comparison integer containing the one bit for that inner loop segment. This example takes more than three seconds to run.  (For a raw 1280 X 720 file, 29,491,200 comparisons.)



Using Left Shifts From One to Get Comparison Value
The same file is again processed below. The only difference is the replacement of 2 ^ lt3 with 1 << lt3. I thought it could be somewhat faster, but did not expect the output file counter on my form to just fly by. But it did, pow, pow, pow, pow, pow -- like that. Less than 300 milliseconds.



Small things can makes a big difference. So, yeah, I guess bit shits are still way faster than arithmetic. I always use parentheses around them, because things get funny otherwise.