Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Find minimum of two integers without branching:</p> <p><a href="http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax" rel="nofollow">http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax</a></p> <blockquote> <p>On some rare machines where branching is very expensive and no condition move instructions exist, the above expression might be faster than the obvious approach, r = (x &lt; y) ? x : y, even though it involves two more instructions. (Typically, the obvious approach is best, though.)</p> </blockquote> <p>Just to kick things off, here's a brain-dead benchmark. I'm trying to get a 50/50 mix of large and small values "at random":</p> <pre><code>#include &lt;iostream&gt; #include &lt;stdint.h&gt; int main() { uint32_t total = 0; uint32_t n = 27465; for (int i = 0; i &lt; 1000*1000*500; ++i) { n *= 30029; // worst PRNG in the world uint32_t a = n &amp; 0x1ffff; #ifdef EMPTY uint16_t b = a; // gives the wrong total, of course. #endif #ifdef NORMAL uint16_t b = (a &gt; 0xffff) ? 0xffff : a; #endif #ifdef RUSLIK uint16_t b = (-(a &gt;&gt; 16) &gt;&gt; 16) | a; #endif #ifdef BITHACK uint16_t b = a ^ ((0xffff ^ a) &amp; -(0xffff &lt; a)); #endif total += b; } std::cout &lt;&lt; total &lt;&lt; "\n"; } </code></pre> <p>On my compiler (gcc 4.3.4 on cygwin with -O3), <code>NORMAL</code> wins, followed by <code>RUSLIK</code>, then <code>BITHACK</code>, respectively 0.3, 0.5 and 0.9 seconds slower than the empty loop. Really this benchmark means nothing, I haven't even checked the emitted code to see whether the compiler's smart enough to outwit me somewhere. But I like ruslik's anyway.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload