docs

You are reading the docs for v0.1.2. Nabi 0.1.2 is no longer supported. Latest release: v0.1.3 →

#Parallel map / reduce

On this page

Split prime counting across cores with map, fold, filter and join from core::par, and check the result against a sequential count.

#Code

#Walkthrough

  • par::map splits the items into chunks processed at the same time on the thread pool, but the result list keeps the input order, so counts[i] is the answer for the block starting at starts[i] (2.19.1 core API, par::map).
  • par::fold folds each chunk first and then folds the chunk results. The function must be associative so that regrouping gives the same answer: addition is, subtraction is not (par::fold). par::reduce(counts, |a, b| a + b) is the same without the 0, and gives none for an empty list (par::reduce).
  • par::filter keeps the order as well, so the primes around one million come out ascending.
  • par::join runs two unrelated computations at once and returns both results as a tuple (Concurrency).
  • Comparing the parallel and sequential answers is the simplest way to check parallelized code. Timings vary from machine to machine, so they are not part of the output.

#Running it

To see the speedup, time an optimized build.

bash
nabic build --release par.nabi -o par
time ./par

Found a mistake? Edit this page on GitHub. Last updated