Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to choose between std::reduce and std::accumulate?

std::accumulate and std::reduce does almost the same thing.

Summary of of std::reduce says it all:

similar to `std::accumulate`, except out of order 

In many cases these functions should yield the same end result and exhibit the same overall functionality. It is obvious that if you have some very heavy load computation, etc. you can experiment with std::reduce for parrelization. Ie. what is the conventional wisdom here from a birds view - should you always stick to the blunt std::accumulate unless explicitly optimizating ? or should just default to use std::reduce ?

If std::reduce (with default/no execution policy chosen) is always at least as fast as std::accumulate (save a few instructions) then I think accumulate should only be used when the order is strict.

like image 939
darune Avatar asked Jan 22 '20 09:01

darune


1 Answers

Yes, I would always use std::reduce unless you know you need the in-order guarantee from std::accumulate. This gives the compiler greater freedom to optimize, and in the worst case is identical anyway.

like image 197
Anthony Williams Avatar answered Sep 24 '22 17:09

Anthony Williams