13 comments

  • orlp9 hours ago
    Since pdqsort (an older project of mine) was mentioned, I felt it wouldn&#x27;t be entirely inappropriate to mention that I&#x27;ve since then collaborated with Lukas Bergdoll to provide two high-quality sort implementations for the Rust standard library, ipnsort (unstable) and driftsort (stable).<p>So if you use Rust, you get these by simply calling [T]::sort(_unstable). Great performance out of the box :)<p>On my machine (Apple M2), using the benchmarks from the repository on Apple clang 17 and Rust 1.98 nightly:<p><pre><code> Sorting 50 million doubles: ipnsort 0.79s blqs 0.90s driftsort 1.13s (stable) std::sort 1.22s std::stable_sort 4.64s (stable) Sorting 50 million (i32, i32) structs: ipnsort 0.82s blqs 0.89s driftsort 1.07s (stable) std::sort 3.09s std::stable_sort 3.15s (stable) </code></pre> And now for a cool party trick, let&#x27;s repeat the 50 million doubles experiment again, but have the first 90% already sorted, last 10% random:<p><pre><code> driftsort 0.29s (stable) ipnsort 0.81s std::sort 1.15s std::stable_sort 1.63s (stable) blqs 1.89s</code></pre>
    • tialaramex30 minutes ago
      Thanks for everything Orson! I know Clang struggled to ship improved sorts for their C++ implementation, so it&#x27;s a good sign that Rust was able to ship ipnsort and driftsort without too much chaos.<p>Also, Lukas looked over my `misfortunate` crate (which provides &quot;perverse&quot; implementations of safe Rust traits) and although misfortunate isn&#x27;t intended for testing he has inspired me to improve the perverse implementations of Ord, not for testing per se but to further illustrate. It occurs to me I should point anybody reading misfortunate&#x27;s documentation at your&#x2F; Lukas&#x27; work in case they actually need really nasty tests not just mild perversion.
    • vintagedave33 minutes ago
      This is very impressive work.<p>I looked at your paper[0] and was curious why it was named &quot;drift&quot; sort. Even searching for &#x27;drift&#x27; didn&#x27;t show me. I mainly ask because this is noted as a stable sort and the word &#x27;drift&#x27; implies movement; I did not expect it, from the name, to be a stable sort.
      • orlp7 minutes ago
        It&#x27;s called driftsort because it&#x27;s derived from another sort I made, glidesort: <a href="https:&#x2F;&#x2F;github.com&#x2F;orlp&#x2F;glidesort" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;orlp&#x2F;glidesort</a>. Glidesort is a bit faster still for large inputs, however it was too large and complex for inclusion in the standard library, and suffered from code size penalties on small inputs. So driftsort is a slimmed down version more appropriate for general purpose.
  • kleiba22 hours ago
    <p><pre><code> for (int i = 0; i &lt; 1000; i++) { small_numbers[smlen] = numbers[i]; smlen += (numbers[i] &lt; 500); } </code></pre> <i>is much faster than the conventional version with a conditional branch:</i><p><pre><code> for (int i = 0; i &lt; 1000; i++) { if (numbers[i] &lt; 500) { small_numbers[smlen] = numbers[i]; smlen += 1; } } </code></pre> Been staring at this for a bit, but my brain is not working properly today: could someone please explain how these to loops compute the same value for small_numbers[smlen]?
    • bhaak11 minutes ago
      They don&#x27;t. After running, for the values in small_numbers from 0 to smlen-1 they are equivalent.<p>But if the last value of numbers[] is not smaller than 500, small_numbers[smlen] will contain that value for the first version whereas the second version does not write to small_numbers[smlen].
    • edelind32 minutes ago
      Here is another perspective:<p>- the first one (branchless) use the condition to SAVE the correct value (&lt; 500): it temporarily writes any current value to the same index i, always overwriting the previous value, effectively saving it (by moving forward to i+1) only when the value is right (small number). Downside of this simple function: the last value may be bigger than 500<p>- the second one use the condition to ADD the value, when it is 100% sure it is a correct small number
    • addaon2 hours ago
      &gt; &quot;these two loops compute the same value&quot;<p>At what sequence point? The branchless version writes to small_numbers[smlen], for any given value of smlen, potentially more than once; so there are observable points of time during the loop where the behavior is different. But after the loop, both contain the final write to small_numbers[i] for all 0 &lt;= I &lt; smlen; and the transient writes both don&#x27;t change observed external behavior, and are apparently cheaper than fewer but conditional writes.
    • jcul1 hour ago
      First version has a side effect of writing to small_numbers[0] always.<p>The compiler probability can&#x27;t optimize that in the second version.<p>If it wrote unconditionally and incremented only in the if then I&#x27;d guess they would compile to the same thing.
    • teo_zero2 hours ago
      Writing to array[n] and not incrementing n means that the value just written is outside the &quot;useful&quot; range (from 0 to n-1) and will not be considered (it will be overwritten the next iteration).
    • zelphirkalt1 hour ago
      I am rather thinking, if one is so much faster, and they are truly equal, why is the compiler too stupid to convert one into the other?
      • flohofwoe55 minutes ago
        The two code snippets do different things, apples and otanges... e.g. the array modification in the second example needs to move in front of the if. I bet then the compiler output is the same with -O1 or higher.
    • gblargg2 hours ago
      It only increments if the number was less than 500, effectively just saving the ones less than 500.
    • defrost2 hours ago
      numbers[i] &lt; 500<p>is a conditional (true or false) that evaluates to 1 or 0 (in C)<p>Therefore smlen has either a 0 or a 1 added to it&#x27;s value .. equivilent to only adding 1 if True.
  • quuxplusone6 hours ago
    It&#x27;s unfortunate that the C++ version of the code assumes the type T is default-constructible (and that the default constructor is cheap). It also assumes that the type T is copy-constructible; at a glance I can&#x27;t tell if the algorithm <i>depends</i> on making a copy in every place that it <i>does</i> make a copy. E.g. in the `heap_sort` helper we have<p><pre><code> T k; &#x2F;&#x2F; default-construct if (i &gt; 0) k = left[--i]; &#x2F;&#x2F; copy-assign </code></pre> This fairly obviously could be replaced with &quot;copy-construct.&quot; Could it be replaced with &quot;move-construct&quot;? I don&#x27;t know. Again, in `partition_small`, we have<p><pre><code> T swbuf[SMALLPART]; </code></pre> which default-constructs a bunch of Ts. I <i>think</i> we&#x27;re just going to overwrite that memory in a moment anyway, so constructing all those Ts is a waste of cycles; but I&#x27;m not sure.<p>All of my &quot;I don&#x27;t knows&quot; and &quot;I&#x27;m not sures&quot; are due to my own lack of digging into the code; I&#x27;m sure one could find out if one really looked.<p>None of that matters if you&#x27;re just sorting `int` or the benchmarked `struct entry`. But it matters a great deal if you&#x27;re taking the README literally and trying to sort &quot;types with higher copy costs [...] (such as strings)&quot;.
    • quuxplusone6 hours ago
      ...Ah, `heap_sort` is used only for trivially copyable types. So my complaint about not distinguishing copy from move is essentially unimportant (matters only in pathological cases that we shouldn&#x27;t worry about).<p>But it&#x27;s perfectly possible for a type to be &quot;trivially copyable&quot; without being &quot;default-constructible.&quot; An example of such a type from the STL: `std::reference_wrapper&lt;int&gt;`.<p>Anyway, looks like a quick fix for this would be to just extend the list of traits on which blqsort is gated (currently `is_trivially_copyable` and `sizeof(T) &lt;= 16`) by adding `is_trivially_default_constructible&lt;T&gt;::value` also.
      • chrka1 hour ago
        Author here. No, it&#x27;s also called from the non_trivially_copyable branch (as a fallback). I&#x27;ll fix that.
      • NooneAtAll33 hours ago
        why such love for copies tho?<p>why look for trivial copy and not trivial move?
  • Tomte1 hour ago
    I‘m always a bit envious when I see those branchless styles. In my day job I have the obligation to hit 100% modified condition&#x2F;decision coverage, and I‘m daydreaming about having just one control flow through everything, in order to save module tests that only test the umpteenth condition combination.<p>Obviously, readable code wins, but at least once I had the computing time budget to be able to have a central function go straight through by calculating all five or so variations (it was about several kinds of encodings of the output values) and just pick the correct one in the end. That felt good.
  • bagxrvxpepzn1 hour ago
    &gt; On modern CPUs, avoiding branch misprediction is a key technique to speed up programs.<p>This is true but it&#x27;s misleading. The reality is that modern out-of-order superscalar CPUs are so good at branch prediction that it&#x27;s nearly always better to branch in a tight loop (to allow more ILP) than introduce a data-dependency in a tight loop (which limits ILP). Cf. <a href="https:&#x2F;&#x2F;mazzo.li&#x2F;posts&#x2F;value-speculation.html" rel="nofollow">https:&#x2F;&#x2F;mazzo.li&#x2F;posts&#x2F;value-speculation.html</a>, <a href="https:&#x2F;&#x2F;yarchive.net&#x2F;comp&#x2F;linux&#x2F;cmov.html" rel="nofollow">https:&#x2F;&#x2F;yarchive.net&#x2F;comp&#x2F;linux&#x2F;cmov.html</a><p>Branchless code should generally be avoided because modern CPUs are not designed to optimize that use case. There are exceptions of course, but those are exceptions.
    • chrka41 minutes ago
      Branchful only wins via ILP when data becomes good predictable. But since Quicksort partitioning aims for a 50&#x2F;50 split, it operates in the worst possible zone for a branch predictor. That&#x27;s why branchless wins here, as proven by the benchmarks.
    • globular-toast50 minutes ago
      I was thinking that... When they say &quot;modern CPUs&quot;, surely that includes any pipelined CPU? Maybe Pentium 4 era long pipelines in particular. But actual modern CPUs are much better at branch prediction.<p>But for something like sorting wouldn&#x27;t the worst case be completely random data which would defeat any kind of branch prediction?
  • mgaunard10 hours ago
    Aren&#x27;t there several bitonic sort network implementations that are vectorized, Intel&#x27;s in particular?<p>Why not compare against that?
    • jeffbee10 hours ago
      Great question. It would also be fair to ask how this behaves with non-random inputs. The benchmarks in the repo only use random values.
    • mswphd9 hours ago
      Funny: you can cf &quot;sorting network&quot;, and see they use them within their own design even.
  • teo_zero2 hours ago
    Nitpicking the C variant:<p>&gt; #define BLQS_CMP(a, b) ((a) &lt; (b))<p>A function that returns true when one operand is Less Than the other, should be called BLQS_LT. The CMP abbreviation is idiomatic for a function that returns -1,0, or 1.
  • davidkwast10 hours ago
    It is so simple that I had to look very slowly to understand. Nicely done.
    • NuclearPM10 hours ago
      If it wasn’t simple you could look fast and understand?
      • hyperhello9 hours ago
        If it wasn&#x27;t simple, there would be more lines of code to implement the same idea. As it is, he might have had to spend an hour understanding one line to understand that idea (1 line&#x2F;hr slow), as opposed to spending an hour reading a hundred lines of code (100 line&#x2F;hr fast) for the same result.
      • Brian_K_White3 hours ago
        Yes.<p>But merely the word simple isn&#x27;t the best. Replace simple with elegant.<p>It can be quite hard to fully and correctly understand a small perfect thing.<p>If it gets 20 different jobs done without 20 different if statements, it&#x27;s small and elegant, and simple to impliment, but not simple to understand (maybe simple to <i>think</i> you understand it.)<p>20 if statements you understand immediately and with no effort.
      • pasquinelli6 hours ago
        kind of the flip side of pascal&#x27;s &quot;I would have written a shorter letter, but I did not have the time.&quot; if someone does have the time to make the letter short, it&#x27;ll take longer to read (where &quot;read&quot; means to grasp the subtleties of.)
  • kvuj7 hours ago
    &gt;On modern CPUs, avoiding branch misprediction is a key technique to speed up programs. This branchless approach:<p>&gt;<p>&gt;for (int i = 0; i &lt; 1000; i++) {<p>&gt; small_numbers[smlen] = numbers[i];<p>&gt; smlen += (numbers[i] &lt; 500);<p>&gt;}<p>Excuse my terrible ignorance but isn&#x27;t there still a branch? If numbers[i] &lt; 500 then 1 else 0? I would think something like addition plus a bit comparison would avoid said branch. Unless compilers already optimize the code, but then wouldn&#x27;t they also optimize the naive piece of code?
    • josephg6 hours ago
      Nah. (numbers[i] &lt; 500) is an expression which evaluates to true (1) or false (0). Evaluating this doesn&#x27;t require a branch. There are instructions on modern CPUs to turn this expression into a number without a conditional jump. (cmp (compare), setle (set if comparison was less than or equal), then add).<p>&gt; then wouldn&#x27;t they also optimize the naive piece of code?<p>Great question. They do sometimes!<p>In general, the problem for compilers is that its not obvious which method would be better in some given piece of code. Most branches are highly predictable. Like, imagine a for loop which counts to 1000. At the end of the loop body, the code branches to see whether we should stay in the loop, or exit the loop. The first 999 times through the loop we keep going - so 99.9% of the time, the branch ends up taking the same path. Its very predictable! CPU designers optimise heavily for this, via branch prediction logic. Highly predictable branches run fast. (This is also why array bounds checking doesn&#x27;t really hurt performance at all.)<p>But the branch predictor really struggles when the condition is unpredictable - ie, when a conditional branch is taken about 50% of the time. As is the case in a sorting algorithm.<p>The compiler has no idea whether any condition in your code is predictable or not. There are hints you can use, but it often defaults to just doing whatever you ask it to do.<p>Here&#x27;s what the compiler actually does with the code you quoted. You can see the extra branch + jump for the second version of the code:<p><a href="https:&#x2F;&#x2F;c.godbolt.org&#x2F;z&#x2F;zv7Tcd49f" rel="nofollow">https:&#x2F;&#x2F;c.godbolt.org&#x2F;z&#x2F;zv7Tcd49f</a><p>I clicked around - for some reason even using __builtin_expect_with_probability, none of the compilers I tried will convert from one version of this code into the other.
      • aw16211073 hours ago
        If you hoist small_numbers[smlen] = numbers[i] out of the if statement then the compiler will produce nearly the same branchless assembly for both cases (the only difference being compare against 499 followed by setle vs. compare against 500 followed by setl).<p>Taking a second look I want to say you need to hoist the assignment for the loops to be semantically identical anyways.
    • rotifer6 hours ago
      At the bottom of the page there&#x27;s a link, &quot;When ‘if’ slows you down, avoid it&quot; [1], that discusses these exact questions. It&#x27;s basically what @josephg said, but it also shows the assembly language for each version.<p>[1] <a href="https:&#x2F;&#x2F;tiki.li&#x2F;blog&#x2F;branchless" rel="nofollow">https:&#x2F;&#x2F;tiki.li&#x2F;blog&#x2F;branchless</a>
    • 4k0hz7 hours ago
      There&#x27;s no branch in that code either way. The comparison operator outputs a value (which is arithmetic, not a branch), and that value is added unconditionally.
      • achandlerwhite6 hours ago
        Isn’t there an implicit check to exit the loop?
        • Tiddles-the2nd6 hours ago
          The check isn&#x27;t important; what&#x27;s important is being predictable so the CPU can guess which way the check will go. I don&#x27;t know exactly how it works, but after the first couple of loops, the predictor will assume it&#x27;s always going to end up in the loop and make that the fast path. It may guess wrong the first couple of loops, and the last check wrong, but the other 997 will be correct.
          • grumbelbart22 hours ago
            There is a static branch predictor that is used if there is no statistic on a branching instruction yet, and it&#x27;s really simple: Jumps <i>backward</i> are assumed to be taken (they usually are from a loop), jumps <i>forward</i> are assumed to be not taken.<p>So the jump that forms the loop will be predicted correctly for all executions but the very last (when the loop ends).
            • Panzer046 minutes ago
              That&#x27;s very cute.<p>I wonder how much more complicated and effective statistical predictors are.
        • cstrahan6 hours ago
          “that code” refers to the body of the loop.<p>Unless the loop is unrolled, yes, there is a branch to exit the loop. But then that doesn’t matter because the whole goal at the beginning was to avoid branch misprediction (which is not the same thing as avoiding branches entirely).
  • globular-toast45 minutes ago
    Anyone interested in branch-free code might like the book <i>Hacker&#x27;s Delight</i>. Lots of examples of stuff like this in there.
    • coldstartops6 minutes ago
      Highly recommend. The exampels are in c&#x2F;c++ and the same concepts can be ported to other languages like golang.<p>My favorite part of it is Chapter 2 the bit manipulation tricks.
  • dekdrop6 hours ago
    If it&#x27;s branch predicting, why would if statement run slow? How come unnecessary memory write is fine?
    • teo_zero2 hours ago
      In modern CPUs a mispredicted branch is much more expensive than a memory write.<p>The unsaid assumption is that the array is filled with random values between 0 and 1000, so the &quot;if&quot; condition has a 50% of chances to be true. The branch is mispredicted 50% of times.<p>Of course this trick won&#x27;t work when the statement protected by &quot;if&quot; is a more complex and costly action, or one that can&#x27;t be undone (in the example, note that when the counter is not incremented, the value written to memory will be overwritten in the next cycle, so it&#x27;s &quot;undone&quot; in a certain way).
    • gblargg2 hours ago
      Modern processors are pipelined, where they run a lot in advance of when the result is needed. A mispredicted branch requires throwing out all the advance calculations on the incorrectly followed path. The branch predictor can&#x27;t predict branches like this based on data that tends to equally be distributed for taken and not taken. The memory write is fine because it&#x27;s not conditional, so it can be pipelined along with everything else.
    • tancop3 hours ago
      [dead]