News for hackers. Stuff that matters.
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.