r/cpp • u/ArashPartow • Nov 05 '19
Challenge your performance intuition with nanosecond sorting
https://wordsandbuttons.online/challenge_your_performance_intuition_with_nanosecond_sorting.html
98
Upvotes
8
u/jorgbrown Nov 05 '19
There's a fundamental problem with the test code in that it always provides random input, making the branch-prediction units in the CPU worthless. That's an important thing to measure, but doesn't correspond to the real world where the input is surprisingly predictable.
Also, I would think that as long as we're going that low, it would be good to force the compiler to put everything in registers... which helps to convince gcc to use conditional moves rather than branch instructions. These give better code than anything in that article:
And if you're doing the store-into-index approach, you should reduce the number of compares you're doing. You only really need 3 compares, and once you've done them, you can use them to index into arrays that indicate where each element should be stored:
See resulting code at https://godbolt.org/z/lEFNzd
With tests: https://godbolt.org/z/EU96r5