8 ms·
Why is it faster to process a sorted array than an unsorted array? (2012)
- LucMomal 9y agoImagine if words in your dictionary wasn't sorted and you will have your answer.
- icebraining 9y agoWhy would you care, if you were reading them sequentially, like the code here is doing?
- deleted 9y ago[deleted]
- wiredfool 9y ago(2012)
- gbrown_ 9y agoDoes this time this was posted really have any relevant bearing on the content here?
- Waterluvian 9y agoOlder posts are regularly shared on Hackernews, because no, time often doesn't matter. But it's still valuable metadata that is usually posted or added to the title.
- fenomas 9y agoAmong other things, for people to whom the title sounds familiar it gives them a hint that it's the same article they remember, not something brand new.
- zeotroph 9y agoI was quite certain that this was the famous post with the railroad junction picture before I followed the link. This was submitted 3 times already (but only sortof gained traction once): https://news.ycombinator.com/item?id=12490893 https://news.ycombinator.com/item?id=12490893 https://news.ycombinator.com/item?id=14459549 https://news.ycombinator.com/item?id=14459549 https://news.ycombinator.com/item?id=12272428 https://news.ycombinator.com/item?id=12272428 I am not against resubmissions, but if it is an older post the year should be in the title.
- jnordwick 9y agoYes. Architecture changes and some of the cmov info is probably incorrect now.
- ballenf 9y agoQuestion and top answer were both edited this year. Didn't look at diff to see how substantively.
- mark-r 9y agoThe recent edits are all trivial. The meat of the question and top answer have been there since 2012.
- minikites 9y agoThis is a fabulous explanation that I think a novice programmer could readily grasp.
- ak39 9y agoAgreed. StackOverflow could make a lovely book with these kind of high quality answers. Stuff's gold.
- wiz21c 9y agoWhen I look at the code, I'm under the impression that will generate always the same output because the random seed is fixed (besides the timer). Given current tech, could a compiler see that and just reduce the computation to a simple value ?
- MichaelBurge 9y agoSort of. If rand() wasn't built into the standard, it would be impossible because you could override it at link-time with another function that connects to your database or something. And the linker runs after the compiler. But because it's built-in, the compiler might be able to infer more about it, just like it reduces: printf("x"); to putchar('x');
- bluejekyll 9y agoThe update at the very end is pretty awesome. Basically saying, some compilers will optimize this for you now so there's no difference. It would be interesting to see how Clang/LLVM do...
- tapatio 9y agoImagine that as an interview question!
- Izmaki 9y agoI can perfectly imagine it as it may give an indication on whether your interest is in the field or not. If you know the answer, chances are you read HN or follow other communities as opposed to not giving a damn.
- mikulas_florek 9y agoWhat are you trying to say?
- Sean1708 9y agoI actually think this would be a very good interview question for someone who would be working on performance critical C++ software (maybe not for an entry-level position though), branch-prediction is something that anyone working in that domain should understand at least the basics of and it could quite easily open up the conversation to other hardware or optimisation topics.
- samfisher83 9y agoYou learn branch prediction in most CS, CE or EE programs.
- tayo42 9y agoWhat kind of class would include that in their curriculum?
- pvarangot 9y agoIt's usually a topic on the first computer architecture class. It's a mid-of-the-book topic on most computer organization books, the classics like Hennesy Patterson or Tanenbaum have substancial portions dedicated to it. Both are books for a first course on computer architecture and design. It's very important to understand it so that you can understand why sometimes pipelining is difficult or impossible.
- samfisher83 9y agoAfter its sorted you could add a break condition when the array is less than 128 that way it would make it faster.
- Kesty 9y agoThis is just a simple example for this kind of situation. Of course, you could make it faster by removing everything under 128 from the array before starting the loop, but it's not really the point here.
- corey_moncure 9y agoThe question I have, which I do not see answered after a quick glance of the top responses, is: What is the total time of sorting + good branch prediction loop, versus not sorting and bad branch prediction loop? Does the good branch prediction save more time than it cost to sort the array, on modern processors? What about old processors with shorter pipelines?
- deleted 9y ago[deleted]
- petters 9y agoWell, the code being measured does one pass through the array. Sorting can in general not be done in linear time, so asymptotically you won't gain anything by sorting first. Edit: Whoops, I misunderstood. Sorry!
- Iburinoc 9y agoWell sure, but from an asymptotic approach both unsorted and sorted are "linear", so asymptotics don't necessarily provide enough information to answer GP's question.
- staticassertion 9y agoI wouldn't expect the cost to offset the impact of having to sort first. But, if you need to process the same data many times, it may be a good idea to sort it up front.
- pletnes 9y agoIn that case, loop fusion may be even more efficient - makes better use of CPU caches. Depends on the logic I suppose.
- staticassertion 9y agoThat's the thing, it's feels impossible to generalize since this can get pretty arbitrary. The size of the data, how sorted the data already is, what you're processing, etc.
- ramshorns 9y agoSome of the suggested ways to avoid the branch are bit manipulation (which is not necessarily portable) and the ternary operator (which seems hardly different from an if-else, though maybe the compiler usually treats it differently). It seems like another way would be sum += data[c] * (data[c] >= 128); which adds 0 when the condition is false.
- mark-r 9y agoMany processors have an instruction that will select between two operands depending on a condition. That can be faster than a branch. Although a sufficiently intelligent compiler would be able to determine that the instruction could be used in an if/else situation.
- gene91 9y agoIt appears to me here that it is trivial for a compiler to use a conditional instruction (instead of a branch) here. As a result, I'm very surprised that it didn't. Any idea why this is the case?
- mortehu 9y agoCorrectly predicted conditional branches are faster than conditional instructions, because they add fewer dependenies. The programmer usually has better knowledge of whether the branch is going to be 50/50 or somewhat predictable, and is thus better suited to make that choice. http://yarchive.net/comp/linux/cmov.html http://yarchive.net/comp/linux/cmov.html
- wyager 9y agoWhile that post is technically correct (conditional moves have high latency because you can't dispatch the instruction until the conditional variable has been evaluated), they're still good in many cases because there's also no immediate dependency on the output of the conditional move. You might end up with 10 conditional moves in your reservation stations, but that's fine if all you're doing is summing up the results. You don't actually act on that sum until the end of your loop, so it's OK if it takes a few cycles after the loop to flush all those pending conditional moves out of the reservation stations.
- jnordwick 9y agoCmov is 1 cycle latency now. Cant remember when there change occurred but AF's info should point the way.
- Veedrac 9y agoThe issue isn't the `cmov` itself, which is extremely forgiving nowadays (4 per cycle!), but the fact the `cmov` introduces a dependency on both inputs and the condition. A predicted branch introduces a dependency on only the predicted input: the other input is never calculated and the condition is checked after-the-fact.
- typon 9y agoExcellent answers
- taeric 9y agoBy far the most interesting part of this post is the update with newer compilers. Intel's compiler, in particular, makes an awesome optimization. Edit: The update is not new, either. Just the part that I found interesting. Apologies for any confusion.
- mikeash 9y agoThanks for pointing that out. I'd seen this before so I wasn't going to bother clicking the link, not knowing there was a cool new thing there.
- taeric 9y agoGlad it was worth clicking. I see I accidentally misled some folks that it was recently updated.
- winstonewert 9y agoThe update with the newer compilers was done back in 2012. There have only been minor changes since then. (Not to say that it isn't interesting, but so that people don't go to the post expecting new content and get disappointed)
- taeric 9y agoI updated to make this clearer at the top level. Thanks!
- jnordwick 9y agoCan you point those out please? I dont see any substantive edits in the last few years. Mostly just changing the notice, bounty award, and a roll back this year.
- taeric 9y agoUpdated my post. I merely meant the section. It was still old. :)
- 9y ago
- localhost 9y agoRead a little further down to WiSaGaN's answer. There's an excellent discussion of the optimizations afforded by the cmovge instruction that is typically generated for the C ternary operator and how its implementation in the CPU pipeline allows it to avoid the branch misprediction penalty. He references a textbook as well "Computer Systems: A Programmer's Perspective (2nd Edition)". Just bought a copy.
- xigency 9y agoSee this also for a case against CMOV predicates: http://yarchive.net/comp/linux/cmov.html http://yarchive.net/comp/linux/cmov.html
- jnordwick 9y agoNeeds a "(2012)" at the end of the title. Also I'm not sure when cmov changed to 1 cycle latency, but it might effect some of the tangential topics here.
- cimi_ 9y agoI had a surprise with sorting in JavaScript a few days ago, details also on SO.[0] TL;DR: Chrome uses quick sort and we managed to hit its worst case by pre-ordering the input alphabetically on the server side. [0] https://stackoverflow.com/questions/46228556/how-is-array-sort-performance-affected-by-the-initial-ordering-of-the-input https://stackoverflow.com/questions/46228556/how-is-array-so...
- xigency 9y agoI'm currently taking an OMS CS course in High Performance Computer Architecture and recently completed the branch prediction lesson. It is a free course on Udacity. Here's the source: https://www.udacity.com/course/high-performance-computer-architecture--ud007 https://www.udacity.com/course/high-performance-computer-arc... Lesson 3 covers pipelines and lesson 4 covers branches. Milos does a great job of explaining "How It Works" for something that is really a hidden layer under the CPU.
- bogomipz 9y agoThanks for sharing, this course looks interesting. Cheers.
- QuotesDante 9y agoMy immediate reaction would be to think of the entropy of the information in the array. Sorted sounds like energy was spent to put more information into that array. Intuitively, the lower entropy of a sorted array should help us predict and make better decisions along the way of searching for things in the array. Completely unsorted arrays give us less information to work with: the lack of order certainly can't help us make decisions!
- matthberg 9y agoThis is a re-occuring duplicate, last posted 3 months ago, then twice again a year ago. Should be tagged [dupe].
- deleted 9y ago[deleted]
- the_evacuator 9y agoTechnically the branch prediction benefit comes from partitioning the array around the critical value 128. Sorting is not necessary. Partitioning may be faster.
- oso2k 9y agoIt's simple. Cache, baby! Cache! To fill in the blanks: Computers, CPU, RAM, and other Storage devices are well optimized for sequential reading and writing.
- known 9y agoCompare with Hash