Max Langhof
Max Langhof

Reputation: 23681

How to parallelize a plain for loop using the C++ standard library

I feel kind of dumb having to ask this, but I just can't find a non-convoluted way to do this.

I have the following loop:

for (int i = 0; i < count; ++i) {
  if (myFunc(i))
    continue;

  myOtherFunc(i);
}

Parallelizing this with OpenMP is trivial: Just add #pragma omp parallel for before the loop.

I wanted to compare the performance of OMP (and its different schedules) to MSVC's parallel <algorithms> implementation (i.e. using C++17 execution policies). The straightforward idea would be to use std::for_each, but I can't figure out a good way to transform this super plain for loop into any appropriate <algorithm> thing that I can throw an execution policy at.

Notably, you can't just do

std::for_each(std::execution::par, 0, count, [](int i){ /*...*/ });

because you must supply iterators (i.e. something that yields the i argument when dereferenced).

Is there some way to match the most plain and basic for loop with <algorithm> tools that doesn't involve silly nonsense?

Upvotes: 10

Views: 6285

Answers (1)

darune
darune

Reputation: 10962

If using , you may use the boost::irange (in ) to produce the counting loop like this:

auto ints = boost::irange(0, count);
std::for_each_n(POLICY, ints.begin(), boost::size(ints), [](int i)
{
  if (!myFunc(i)) {
    myOtherFunc(i);
  }
}
);

Upvotes: 3

Related Questions