parallel_for and partitioners
Turning a loop into parallel work with oneTBB, and what a partitioner decides on your behalf.
- Write a tbb::parallel_for over a blocked_range
- Explain what the static and the default partitioner each do with the range
- Predict when the choice of partitioner does not matter
The programs in 0_even_job_length/ build a list of \(2^{18} = 262{,}144\) jobs, each lasting a random 20 to 30 microseconds:
std::mt19937 mt(rd());
std::uniform_int_distribution bin(20, 30);
int num_work_items = 1 << 18;
std::vector<int> work_items;
std::generate_n(std::back_inserter(work_items), num_work_items,
[&] { return bin(mt); });
and then process them in parallel:
tbb::parallel_for(
tbb::blocked_range<int>(0, num_work_items),
[&](tbb::blocked_range<int> r) {
for (int i = r.begin(); i < r.end(); i++)
std::this_thread::sleep_for(std::chrono::microseconds(work_items[i]));
},
tbb::static_partitioner()); // omitted in 1_dynamic.cpp
parallel_for never sees individual indices. It hands the lambda sub-ranges [r.begin(), r.end()) and the lambda loops over each one. Which sub-ranges exist, and which thread gets each, is the partitioner’s decision:
-
tbb::static_partitioner()cuts the range into one contiguous block per thread before anything runs. There is no coordination after that — cheap, and fully predictable. - With no partitioner argument, oneTBB uses
auto_partitioner: it splits the range in halves on demand, and threads that run out of work steal pieces from busy ones. That costs a little bookkeeping but adapts to whatever happens at run time.
Even jobs: a tie
When every job takes about as long as every other, a block of \(N/T\) jobs takes about \(N/T\) times the average, on every thread. Static scheduling is already balanced, and there is nothing for stealing to fix. That is the conclusion written at the end of 1_dynamic.cpp, and the measurements agree:
| CPUs | static_partitioner | default |
|---|---|---|
| 4 | 7.72 s | 7.77 s |
| 16 | 2.21 s | 2.16 s |
Both versions are within 2% of each other. These times are much longer than the work implies — 262,144 jobs of 25 µs is 6.6 s of work, or 1.6 s on four CPUs — and the reason is the sleep_for overhead discussed in lesson 2.
Two small fixes in the repository
- The files call
std::this_thread::sleep_forwithout#include <thread>(and the uneven-length ones also omit<chrono>). They compile because the oneTBB headers happen to include them; adding the includes keeps them compiling with other library versions. - The jobs are seeded from
std::random_device, so every run gets different job lengths. A fixed seed,std::mt19937 mt(42), makes timings comparable between runs.
Try it yourself. Add tbb::simple_partitioner() with a grain size, tbb::blocked_range<int>(0, num_work_items, 1), and time it. Every job is now its own task: compare it with the default and explain the difference in terms of scheduling overhead per task. Then try a grain of 4,096.