2

Is there a simple function in the ppl library for C++ where you can do something like Concurrency::max(vec) where vec is a vector of numbers? I can write my own, but I was hoping I could save myself the work.

Edit: Sorry I was not clear enough maybe. I need the max function to utilize parallelization.

spurra
  • 1,007
  • 2
  • 13
  • 38
  • Looks like you need to [do a map-reduce](http://msdn.microsoft.com/en-us/library/hh873179.aspx), but to be honest this is really a partition divide and conquer issue. – Mgetz Apr 08 '14 at 14:10
  • I don't see how I could use map-reduce. Guess I'll have to write my own divide-and-conquer approach. – spurra Apr 08 '14 at 14:16
  • 1
    Well to be brutally honest, unless this vector is on the order of gigabytes and is partially swapped to disk. A single threaded approach using a [value based `max`](http://randomascii.wordpress.com/2013/11/24/stdmin-causing-three-times-slowdown-on-vc/) is likely to beat anything in parallel. A modern CPU is very very optimized for this kind of thing. – Mgetz Apr 08 '14 at 14:20

2 Answers2

2

There is nothing built in, but it's straightforward with combinable (a reduction variable) and a parallel loop (here parallel_for_each). However if the work you are doing is only 'max' of numbers unless the amount of numbers you are looking at is very large, it may be difficult to see speedups.

You can read more about it on msdn:

#include <ppl.h>
#include <climits>
#include <vector>
#include <numeric>
#include <iostream>
using namespace Concurrency;
int main(int argc, _TCHAR* argv[])
{
    std::vector<int> vec(10);
    std::iota( begin(vec), end(vec), 1);
    combinable<int> locals([]{ return INT_MIN; });
    parallel_for_each( begin(vec), end(vec), [&locals](int cur){
        auto & localMax = locals.local();
        localMax = std::max(cur, localMax);
    });
    std::cout << "max is " << locals.combine([](int left, int right){ return std::max<int>(left, right);}) << std::endl;
    return 0;
}
Rick
  • 3,285
  • 17
  • 17
0

Is it just a std::vector? If so you can use max_element.

auto it = std::max_element(std::begin(vec), std::end(vec));

The iterator it then points at the vector element that has the maximum value.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • Does this run in parallel? – spurra Apr 08 '14 at 13:58
  • For a single vector `vec` no I don't believe so. It basically just walks the entire vector from `begin()` to `end()` and keeps track of the max element. – Cory Kramer Apr 08 '14 at 13:59
  • My apologies for not being clear enough. I would like the max function to utilize all my CPU Cores. The vector I'm traversing through is rather large. – spurra Apr 08 '14 at 14:01