News for hackers. Stuff that matters.
Re:Clever code is probably the worst code you could write by a_t48 on Tuesday May 21, 2024 @06:53PM (#40435079)
We now have

       return std::reduce(x.begin(), x.end());
Which is a little cleaner and is even faster (compiler is free to do the additions in any order). https://en.cppreference.com/w/cpp/algorithm/reduce - it looks like even the `accumulate` example can be made simpler with `std::plus`. I prefer the `reduce` option for a number of reasons, but understand why someone might not.
Re:Clever code is probably the worst code you could write by floxy on Tuesday May 21, 2024 @07:34PM (#40435557)
>the `accumulate` example can be made simpler with `std::plus`

Accumulate, surprisingly enough, accumulates by default:

    return accumulate(x.begin(), x.end(), 0);
Re:Clever code is probably the worst code you could write by MathMonkeyMan on Tuesday May 21, 2024 @08:24PM (#40435971)
Just make sure you're accumulating integers and not doubles!
Re:Clever code is probably the worst code you could write by a_t48 on Wednesday May 22, 2024 @12:41AM (#40437411)
Obviously, you have to use

   std::accumulate(v.cbegin(), v.cend(), decltype(*v.cbegin()){});
:) :) :)
Re:Clever code is probably the worst code you could write by floxy on Thursday May 23, 2024 @12:52AM (#40450601)

  #include<cstdio>
  #include<numeric>
  #include<vector>
  
  using namespace std;
  
  template <class T, template<class> class Cont>
  T sum(Cont<T> x)
  {
    return accumulate(x.begin(), x.end(), (T)0);
  }
    
  int main(int argc, char *argv[])
  {
    vector<double> ds({1.1, 2.2, 3.3, 4.4}); 
    vector<float> fs({1.1f, 2.2f, 3.3f, 4.4f});
    vector<int> is({1, 2, 3, 4});
    vector<unsigned long long> ulls({1ul, 2ul, 3ul, 4ul});

    printf("doubles: %f\n",sum(ds));
    printf("floats: %f\n",sum(fs));
    printf("ints: %d\n",sum(is));
    printf("ulls: %llu\n",sum(ulls));

    return 0;
  }
Re:Clever code is probably the worst code you could write by autoexecbat on Tuesday May 21, 2024 @07:05PM (#40435218)
I think most people would be thinking "hmm now I need to read what 'reduce' mean in this context"
Re:Clever code is probably the worst code you could write by jacoblambda on Tuesday May 21, 2024 @07:19PM (#40435397)
At least in my experience in the C++ world there is a general expectation that you learn the "standard algorithms" and prefer them over the alternatives unless you have a specific reason not to.

For example: outside the C++ ecosystem, most people probably would stare blank faced if they saw `std::rotate` in a codebase but it's basically a meme at this point in the C++ space.

Ex: https://www.youtube.com/watch?v=UZmeDQL4LaE

Re:Clever code is probably the worst code you could write by a_t48 on Tuesday May 21, 2024 @07:17PM (#40435364)
For at least the first time, yeah.
Re:Clever code is probably the worst code you could write by j1elo on Tuesday May 21, 2024 @07:17PM (#40435358)
Look at that link:

  2,4,6) ...
  These overloads participate in overload resolution only if
  std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> is true.
  std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>> is true.
std::is_execution_policy_v? std::decay_t? std::remove_cvref_t?

Really, this madness with C++ needs to stop. People who work on newer versions of the language might be very conservative with the language syntax itself, but they clearly decided having carte blanche to adding an infinite amount of stuff to the standard library.

Could someone please force them to stop, somehow? The whole rest of the industry would be thankful.

Re:Clever code is probably the worst code you could write by lupire on Tuesday May 21, 2024 @07:18PM (#40435382)
That's terrible! The main operation, addition, is completely hidden magic! But the completely trivial calls to .begin() and .end() are explicit!

Why would I want to add by default?

Re:Clever code is probably the worst code you could write by jcelerier on Tuesday May 21, 2024 @08:40PM (#40436074)
> The main operation, addition, is completely hidden magic

the main operation is reduction which is fairly basic computer science and taught in any non-BS curriculum - https://en.wikipedia.org/wiki/Reduction_operator (or https://en.wikipedia.org/wiki/Fold_(higher-order_function) which is the standard way to introduce this concept ; check in particular the table showcasing all the implementations in various languages). The standard reduction for a set of numbers to a number that is likely going to be the very first example in your textbook is addition.

Re:Clever code is probably the worst code you could write by Dylan16807 on Tuesday May 21, 2024 @09:26PM (#40436390)
The reduction is explicit. That's not what the complaint is about. And it's more about implementation than the actual result.

The actual operation is addition. I don't care if it's the first example, that doesn't mean you should hide it.

Imagine if print did hello world by default.

Re:Clever code is probably the worst code you could write by o11c on Tuesday May 21, 2024 @08:57PM (#40436181)
std::ranges::fold_left (since C++23) can take a range directly instead of a separated pair of iterators, and requires the explicit add.
Re:Clever code is probably the worst code you could write by psychoslave on Wednesday May 22, 2024 @09:32AM (#40440749)
Maybe the idea is that you overload your favored default as a + operator? Even more baffling certainly, but at this point I wouldn’t even be surprised this was considered a compelling argument in the mind of whoever settled this API choice. :D
Re:Clever code is probably the worst code you could write by constantcrying on Wednesday May 22, 2024 @11:28AM (#40442184)
What is hidden? It's a reduce on + starting with 0, hardly anything subtle.
Re:Clever code is probably the worst code you could write by vlovich123 on Tuesday May 21, 2024 @08:26PM (#40435982)
> and is even faster (compiler is free to do the additions in any order)

Is that actually true? I'm not even sure how hypothetically removing ordering requirements would help you extract performance, let alone any compilers that could do anything with that today. Unless the standard library were to auto-parallelize the reduction, but I doubt they'd do that because the overhead of starting threads would be quite costly for anything but the absolute largest ranges since C++ doesn't have a thread pool sitting idly for you (not to mention that the docs for the function don't mention any thread safety requirements for the BinaryOp and Init which would be required for any such optimization).

Re:Clever code is probably the worst code you could write by a_t48 on Tuesday May 21, 2024 @10:53PM (#40436885)
The linked page has benchmarks - I'd have to go dig into godbolt to see why it's faster. The standard library can actually auto-parallelize, but you have to opt in (see the ExecutionPolicy argument).

Edit: I don't know how to dig into the actual implementation of std::reduce on godbolt - it's not inlined. I think the sibling comment has it right though - one can do adds of four at a time with whatever SIMD extensions are available.

Re:Clever code is probably the worst code you could write by im3w1l on Tuesday May 21, 2024 @08:38PM (#40436065)
I think relaxing the ordering requirement let's you use simd something like this (semi-pseudo code)

  (a, b, c, d) = (0, 0, 0, 0);
  for(int i = 0; i < n; i += 4) {
    (a, b, c, d) += (arr[i], arr[i+1], arr[i+2], arr[i+3]);
  }
  return a + b + c + d;
Re:Clever code is probably the worst code you could write by mjcohen on Wednesday May 22, 2024 @01:08PM (#40443385)
What if n is not a multiple of 4? There is a trick I can't recall at the moment for handling this with a case statement on n mod 4 at the end to wrap this up.
Re:Clever code is probably the worst code you could write by jbboehr on Thursday May 23, 2024 @03:46AM (#40451753)
Re:Clever code is probably the worst code you could write by vlovich123 on Wednesday May 22, 2024 @01:37PM (#40443736)
Are you sure that the compiler doesn’t autovectorize a simple loop into this form anyway? This is kind of the defacto scenario for that pass.
Re:Clever code is probably the worst code you could write by im3w1l on Wednesday May 22, 2024 @03:23PM (#40445124)
This transformation is only legal if order of summation doesn't matter. So the compiler can do it for ints, but not floats.
Re:Clever code is probably the worst code you could write by vlovich123 on Wednesday May 22, 2024 @09:54PM (#40449501)
Applying std::reduce to floats would be a similarly bad idea for having the compiler do it, except people will write it without thinking. Of course, people always struggle with writing correct floating point so I doubt it makes things better or worse, but it’s conceptually the library equivalent of -fast-math (which coincidentally would also auto-vectorize the loop but can impact more than just that).
Re:Clever code is probably the worst code you could write by im3w1l on Thursday May 23, 2024 @02:51PM (#40458414)
Using fast math in one particular expression is way different and less risky than doing it globally.
Re:Clever code is probably the worst code you could write by zarathustreal on Tuesday May 21, 2024 @09:16PM (#40436310)
You answered the question yourself..can you at least edit your comment so you won’t confuse otherwise correctly oriented computer science practitioners?

The commutative property is fundamental to understanding algebraic structures and fast parallel processing. If a binary operation is commutative over a given set then, yes, a proper compiler will parallelize it. No, it will not necessarily use OS threads directly one to one, that’s usually not a consideration even for a naive approach.