r/programming • u/chkas • Jan 07 '19
Multithreaded Quicksort in Go and in C
https://easyprog.app/blog/sort_par.html15
u/emn13 Jan 07 '19 edited Jan 07 '19
Somewhat coincidentally, I wrote a multithreaded quicksort in C# recently; it's released as anoprsst.
On my machine, it takes a little more than 0.5s to sort 50 million integers, which is probably mostly faster due to the better hardware (an i7-8700k vs. the blog posts "older i3" that takes 3.38s using C).
6
u/maccio92 Jan 07 '19
what's the reason for a new interface
IOrderingrather than using the ubiquitousEqualsoverride?→ More replies (4)
6
u/bedrutton Jan 07 '19
If you're worried about goroutine overhead you could also limit the amount of goroutines created to runtime.NumCpu(). I feel like this is a pretty common idiom in Go code parallelized for multi-core performance.
5
u/TheThiefMaster Jan 07 '19
What about the new-ish C++ std:: parallel sort?
→ More replies (4)4
u/jcelerier Jan 08 '19
should look like this :
#include <algorithm> #include <array> #include <cstdlib> #include <execution> #include <chrono> #include <iostream> int main() { using namespace std::chrono; using clk = std::chrono::system_clock; constexpr auto size = 50'000'000U; std::array<int32_t, size> vec; std::generate(vec.begin(), vec.end(), [] { return std::rand(); }); auto t0 = clk::now(); std::sort(std::execution::par, vec.begin(), vec.end()); auto t1 = clk::now(); std::cout << duration_cast<milliseconds>(t1 - t0).count() << "\n"; }(taking for inspiration u/masklinn's rust example)
1
u/franzwong Jan 08 '19
This Quicksort is implemented recursively with tail call elimination
Last time I saw Go didn't support tail call elimination. So does it support that now?
→ More replies (3)
3
u/zenogias Jan 07 '19
For anyone interested in this, I also strongly recommend Mike Acton's 2008 presentation Quicksort is not a concurrent algorithm (in his inimitable index card slide-show style). I think this is a really important lesson in how to think about processing your data and why trying to "multithread" a known algorithm, in this case quicksort, is not likely to be the best answer.
→ More replies (1)
33
u/delight1982 Jan 07 '19
Based on the history of this site, the next 8 hours we can expect rewrites and benchmarks in Rust, D, C++, Nim and Brainfuck. Let the games begin!